Exercise 210

Resume the previous exercise (Exercise 209) without using the intersection() and union() methods.

Solution

A = {11, 21, 5, 7, 43, 32, 13, 9}
B = {2, 19, 11, 33, 7, 25, 5, 4}
C = {45,27,11,5,7,22,14,1}

# Initialization of the intersection of the three sets
I = set({})

for x in A:
if x in B and x in C:
I.add(x)
# display the intersection of the three sets
print(I)

# Initialization of the union of the three sets
R = set({}) # output: {11, 5, 7}

for x in A:
for y in B:
for z in C:
R.add(x)
R.add(y)
R.add(z)
# display the union of the three sets A, B and C
print(R)
# output: {32, 33, 1, 2, 4, 5, 7, 9, 11, 43, 45, 14, 13, 19, 21, 22, 25, 27}

Younes Derfoufi
my-courses.net

Leave a Reply