X=set([1,2,3,4,5])
C=set(['Ithaca','Boston','Chicago'])
Stuff=set([1,'snow','Cornell','y'])
emptyset = set()
1 in X
1 not in C
def is_even(x): return(x%2 == 0) #x%2 is the remainder after division by 2
is_even(4),is_even(21)
len(X), len(C), len(Stuff), len(emptyset) #cardinalities
Cp=set(['Ithaca','Chicago']) #C' in notes
Xp=set(range(2,6)) #X' in notes
Xp
A=set([1,2,3])
X.isdisjoint(C), Cp.isdisjoint(C)
Cp <= C, Cp.issubset(C) #both mean is subset
C<=C, C<C #test for proper and improper subsets
Cp != C, Cp == C #tests for set equality
def powerset(S):
R=[]
B=list(S)
n=len(S)
for i in range(2**n):
x= binary_repr(i,width=n) #e.g. '010' for i=2,width=3
R.append(tuple([B[j] for j in range(n) if x[j] == '1']))
return(set(R))
powerset(A)
sorted(list(powerset(A)),key=len) #subsets sorted by cardinality
X | Stuff # union
C | emptyset #union
A | X #union
(A|X) == X, A.union(X) == X #test whether A union X is equal to X
X & Stuff # intersection
X.intersection(Stuff) #same thing
C & emptyset
A & X
X-Stuff #set difference
C-emptyset
X^Stuff #symmetric difference
C^emptyset
X^A
A
def cartesian_product(S1,S2): return {(a,b) for a in list(S1) for b in list(S2)}
cartesian_product(A,A)
The following examples are from some of the online docs
a = set('abracadabra')
b = set('alacazam')
a # unique letters in a
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
fruit = set(basket)
'orange' in fruit, 'crabgrass' in fruit
{x for x in 'abracadabra' if x not in 'abc'}
a-b # letters in a but not in b
a|b # letters in either a or b
a&b # letters in both a and b
a^b # letters in a or b but not both