Unix -Python-courses-Solaris, Linux, FreeBSD, AIX, HP-Python-courses-UX

Exercise 203

Write a python program as a function that determines the union of two sets without using any predefined functions. Example if

E = {"Lenovo", "Hp", "del" , "Accent" , "Asus"}

and

F = {"Acer", "Thomson"}

, the function returns the set:

{"Lenovo", "Hp", "del" , "Accent" , "Asus" , "Acer", "Thomson"}

Solution

def unionSets(E , F):

# initializing the union of sets
E_union_F = set({})
# adding all element of E to the union
for x in E:
E_union_F.add(x)

# adding all element of F to the union
for x in F:
E_union_F.add(x)

return E_union_F

# Testing algorithm
E = {"Lenovo", "Hp", "del" , "Accent" , "Asus"}
F = {"Acer", "Thomson"}
print("E_union_F = " , unionSets(E , F))
# display: E_union_F = {'Lenovo', 'Thomson', 'Acer', 'Hp', 'del', 'Accent', 'Asus'}

Younes Derfoufi
my-courses.net

Leave a Reply