Exercise206

Given two sets A = {'a' , 'b' , 'c' , 'd'} and B = {'c' , 'e' , 'd' , 'h'}. Write a Python program that returns their symmetric difference without using the python symmetric_difference() method.

Solution

A={'a', 'b', 'c', 'd'}
B={'c', 'e', 'd', 'h'}

# initialize symmetric difference
symmetric_diff = set({})

# difference A - B
for x in A:
if x not in B:
symmetric_diff.add(x)

# difference B - A (the elements of B which do not belong to A)
for x in B:
if x not in A:
symmetric_diff.add(x)

# Show symmetric difference
print("symmetric difference = ", symmetric_diff)
# output: symmetric difference = {'e', 'h', 'b', 'a'}
Younes Derfoufi
my-courses.net

Leave a Reply