# File: ChapterLists/sets.py # Sets: union, intersection, include, disjoint, difference, product """ A = set([ 3, 1, 4, 2 ]) -> A ={3,1,4} B = set([3,7,4]) -> B = {3,7,4} >>> A - B # in A but not in B - difference >>> A | B # either A or B - union >>> A & B # in both A and B - intersection >>> A ^ B # in A or B but not both def unique(a): return list(set(a)) def intersect(a, b): return list(set(a) & set(b)) def union(a, b): return list(set(a) | set(b)) """ def removeDup(L): res = [] for i in range(len(L)): if (L[i] not in L[i+1:]): res.append(L[i]) return res def main(): print(removeDup([2,3,2,3,4,2])) #[3,4,2] L1 =[ 3, 1, 4, 2 ] L2 = [3,7,4] #intersection Int = [x for x in L1 if x in L2] print(L1,L2,'Intersection:',Int) #[3,4] #union Un = [] [Un.append(x) for x in L1+L2 if x not in Un] #remove dups from a list print(L1,L2,'Union:',Un) #[3,1,4,2,7] #difference L1 - L2 Dif = [ x for x in L1 if x not in L2 ] print(L1,L2,'Difference:',Dif) # [1,2] #inclusion L1 < L2 Inc = ([ x for x in L1 if x in L2 ] == L1) print(L1,L2,'Inclusion:',Inc) # False #disjoint L1 int L2 if [ x for x in L1 if x not in L2 ]: print(L1,L2,'Disjoint:',False) #False #cartesian product L1 x L2 Prod = [ [x,y] for x in L1 for y in L2 ] print(L1,L2,'Cartesian product:',Prod) main()