Using IDLE (Python GUI) # 5. set_intersection returns the intersection of two se
ID: 673203 • Letter: U
Question
Using IDLE (Python GUI)
# 5. set_intersection returns the intersection of two sets
# Input: Three lists set_a, set_b, set_u
# Output: A list with the intersection of the two sets
# if set_a and set_b are not subsets of set_u the method returns None
def set_intersection(set_a, set_b):
return
#print set_intersection(["a","b","c","d"], ["a", "b", "k"])
#>>> ['a', 'b']
# 6. set_difference returns the difference of two sets
# Hint: a rule of sets allows to calculate the difference of two sets as the intersection of the complement (check class module on sets)
# Input: Three lists set_a, set_b, set_u (set_u is the universal set, set_a, and set_b must be subsets of set_u
# Output: A list with the difference set_a - set_b
# If set_a and set_b are not subsets of set_u the method returns None
def set_difference(set_a, set_b, set_u):
return
#print set_difference(["b","c","a"], ["a", "b", "k"],["a", "b", "c", "k"])
#>>>['c']
#print set_difference(["a", "b", "k"], ["b","c","a"], ["a", "b", "c", "k"])
#>>>['k']
# 7. set_difference returns the symmetric difference of two sets
# Hint: a rule of sets allows to calculate the difference of two sets based on intersection, union and complement
# Input: Three lists set_a, set_b, set_u (set_u is the universal set, set_a, and set_b must be subsets of set_u
# Output: A list with the difference set_a symm_diff set_b
# If set_a and set_b are not subsets of set_u the method returns None
def symmetric_difference(set_a, set_b, set_u):
return
#print symmetric_difference(["a", "b", "k"], ["b","c","a"], ["a", "b", "c", "k"])
#>>>['k', 'c']
# 8. cartesian_product returns the cartesian product of two sets
# Input: Two lists set_a, set_b
# Output: A list of tuples with the cartesian product of set_a and set_b
def cartesian_product(set_a, set_b):
return
#print cartesian_product(["a","b","c"], ["d","e", "f"])
#>>>[('a', 'd'), ('a', 'e'), ('a', 'f'), ('b', 'd'), ('b', 'e'), ('b', 'f'), ('c', 'd'), ('c', 'e'), ('c', 'f')]
Explanation / Answer
5)
def set_intersection(set_a, set_b):
if set(set_a).issubset(set_u) and set(set_b).issubset(set_u) :
return list(set(set_a) & set(set_b))
return None
6)
def set_difference(set_a, set_b, set_u):
if set(set_a).issubset(set_u) and set(set_b).issubset(set_u) :
return list(set(set_a).difference(set(set_b)))
return None
7)
def symmetric_difference(set_a, set_b, set_u):
if set(set_a).issubset(set_u) and set(set_b).issubset(set_u) :
return list(set(set_a).symmetric_difference(set(set_b)))
return None
8)
import itertools
def cartesian_product(set_a, set_b):
return list(itertools.product(set_a,b))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.