As I explained in my previous Learning Python tutorial in people.Revoledu.com, Python has build-in Set as primitive data type along with list, tuple and dictionary. Thus, set operations like union (|), intersection (&), set difference (-) and symmetric difference (^) are natural in Python.
In this note, let us explore Set Theory in Python. Thus, we start with Set Theory as part of Discrete Mathematics and we want to explore how to represent it in Python.
To use Venn diagram in Python, you might need to install matplotlib-venn. The source code and documentation of this module is in GitHub.
In Command prompt or Anaconda prompt, type:
pip install matplotlib-venn
If you are using Google Colab, add an exclamation ! before pip
!pip install matplotlib-venn
After the installation, now you can import the libraries
from matplotlib_venn import venn2, venn2_circles, venn2_unweighted
from matplotlib_venn import venn3, venn3_circles
from matplotlib import pyplot as plt
%matplotlib inline
Here is my functions to draw Venn diagrams with listing the few elements inside the diagram.
def drawVenn2(A,B,labels = ('A', 'B')):
'''
listing elements in Venn diagram of two sets
'''
v2=venn2([A,B],set_labels = labels);
v2.get_label_by_id('01').set_text(', '.join(map(str,B-A)))
v2.get_label_by_id('10').set_text(', '.join(map(str,A-B)))
if A&B:
v2.get_label_by_id('11').set_text(', '.join(map(str,A&B)))
def drawVenn3(A,B,C,labels = ('A', 'B', 'C')):
'''
listing elements in Venn diagram of three sets, A, B, C
'''
v3=venn3([A,B,C],set_labels = labels);
if A-B-C:
v3.get_label_by_id('100').set_text('\n'.join(map(str,A-B-C)))
v3.get_patch_by_id('100').set_alpha(0.6)
v3.get_patch_by_id('100').set_facecolor('Yellow')
if A&B-C:
v3.get_label_by_id('110').set_text('\n'.join(map(str,A&B-C)))
v3.get_patch_by_id('110').set_alpha(0.3)
v3.get_patch_by_id('110').set_facecolor('Red')
if B-C-A:
v3.get_label_by_id('010').set_text('\n'.join(map(str,B-C-A)))
v3.get_patch_by_id('010').set_alpha(0.6)
v3.get_patch_by_id('010').set_facecolor('Magenta')
if A&C-B:
v3.get_label_by_id('101').set_text('\n'.join(map(str,A&C-B)))
v3.get_patch_by_id('101').set_alpha(0.3)
v3.get_patch_by_id('101').set_facecolor('Green')
if A&B&C:
v3.get_label_by_id('111').set_text('\n'.join(map(str,A&B&C)))
v3.get_patch_by_id('111').set_alpha(0.1)
v3.get_patch_by_id('111').set_facecolor('Black')
if B&C-A:
v3.get_label_by_id('011').set_text('\n'.join(map(str,B&C-A)))
v3.get_patch_by_id('011').set_alpha(0.3)
v3.get_patch_by_id('011').set_facecolor('Blue')
if C-B-A:
v3.get_label_by_id('001').set_text('\n'.join(map(str,C-B-A)))
v3.get_patch_by_id('001').set_alpha(0.6)
v3.get_patch_by_id('001').set_facecolor('Cyan')
A set is a well-defined unordered collection with distinct objects. The objects are also called elements or items. The elements of a set are no duplicate objects.
Mathematically, we can describe a set either:
For example, $A=\left \{ 1,4,9,16 \right \} = \left \{ x^2 | x \in \mathbb{N}, x^2 \leq 20 \right \}$ where the universal set $\mathbb{U}$ is now a set of natural number $\mathbb{N}$ and the property $\textit{P}(x)$ is defined as $x^2 \leq 20 $.
In Python, a set is created by listing the elements in a pair of curly bracket.
In the example below, we define set A by listing the elements but it contains repetitive elements. Python automatically removes the duplicate elements and make them all distinct objects.
A={3, 4, 8, 12, 8, 2, 3, 4, 12, 3, 4} # it contains repetitions
print(A) # Python automatically remove the repetitions and make them distinct
{2, 3, 4, 8, 12}
In the example below, we would like to show that a set is unordered collection. Order in a set does not matter. Python automatically reorder the elements of the set.
F={'durian','kiwi','apple', 'banana', 'cherry'}
print(F) # Python automatially reorder the members of the set
{'banana', 'apple', 'durian', 'cherry', 'kiwi'}
The universal set $\mathbb{U}$ is the set containing all objects or elements and of which all other sets are subsets. The Universal Set is the equivalent to logical value TRUE.
For example, $A=\left \{ 1,2,3 \right \} = \left \{ x | x \in \mathbb{Z}, 1 \leq x \leq 3 \right \}$ where the universal set $\mathbb{U}$ is now a set of integer $\mathbb{Z}$ and the property $\textit{P}(x)=1 \leq x \leq 3 $.
Notice that when we change the universal set $\mathbb{U}$ into the set of real number $\mathbb{R}$, such that $A=\left \{ x | x \in \mathbb{R}, 1 \leq x \leq 3 \right \}$, then the set has infinite members, it is no longer finite set.
If the sets are known, we can define the universal set simply by taking the union of all known sets such that all the known sets become its subset.
A={1,3,6,8}
B={2,3,4,5}
C={5,8,9}
# now we want to find the universal set of the three sets above
U=set()
U=U.union(A,B,C)
U
{1, 2, 3, 4, 5, 6, 8, 9}
Now we can test our definition of universal set
print('is A subset of U? ',A.issubset(U))
print('is B subset of U? ',B.issubset(U))
print('is C subset of U? ',C.issubset(U))
print('is U subset of U? ',U.issubset(U))
E=set() # empty set
print('is Empty set subset of U? ',E.issubset(U))
is A subset of U? True is B subset of U? True is C subset of U? True is U subset of U? True is Empty set subset of U? True
The empty set or null set, denoted as $\varnothing$ or $\left \{ \right \}$, is a set that contain no element. The empty set is the equivalent to logical value FALSE.
In Python, when we define a set, it is an empty set
C=set()
C
set()
We can also define an empty set in Python as the following example.
C={}
C
{}
The cardinality of an empty set is zero: $\left | \varnothing \right |=0$
C={}
len(C)
0
Note that a set containing zero is not an empty set $\left \{ 0 \right \} \neq \varnothing $ because it has one element.
Z={0}
len(Z)
1
We usually use capital letters such as $A, B, ..., X, Y, Z$ to represent set variables and lowercase letters such as $a, b,..., x, y, z$ to represent elements. Mathematically, we write $x$ is an element of set $A$ as $x \in A$.
How do we represent "is an element of set" in Python?
Use in operator.
F={'durian','kiwi','apple', 'banana', 'cherry'}
'apple' in F
True
If $x$ is not an element of set $A$, we write mathematically as $a \notin A$.
How do we represent "is not an element of set" in Python?
Use not in operator.
F={'durian','kiwi','apple', 'banana', 'cherry'}
print('apple' not in F)
print('grape' not in F)
False True
Let $A$ be a finite set with $n$ distinct elements, where $n \geq 0$. Then $\left | A \right | =n$ , where the cardinality (number of elements) of $A$ is $n$.
A set with only one element is called a singleton.
In Python, we can use len() function to get the nmber of elements of a set.
A={'a','b','c','d', 'e', 'f', 'g'}
len(A)
7
A={}
len(A)
0
While we cannot have a set of sets in Python, we can have a set of tuples.
C = {1, (2), ((4, 5), 6), ('red', 'blue', 'yellow')}
len(C)
4
If $A$ and $B$ are sets from a universe $\mathbb{U}$, then $A$ is a subset of $B$, denoted as $A \subseteq B$, happens if and only if every element of $A$ is also an element of $B$. We can formalize this definition as
$A \subseteq B \Leftrightarrow \forall x \left ( x \in A \rightarrow x \in B \right )$
Cardinality for finite set: $ A \subseteq B \rightarrow \left | A \right | \leqslant \left | B \right |$
How do we represent "is A a subset of B" in Python? Use set method issubset()
A.issubset(B)
Alternatively, we can also use <= operator
A < = B
F={'durian','kiwi','apple', 'banana', 'cherry'}
G={'apple', 'banana', 'cherry'}
print('is F a subset of G?', F.issubset(G))
print('is G a subset of F?', G.issubset(F))
print('is G a subset of G itself?',G.issubset(G))
is F a subset of G? False is G a subset of F? True is G a subset of G itself? True
X = {'a','e','i','o','u'}
Y = {'a', 'i', 'u'}
Z= {'b','c','d','f','g'}
print('is Y a subset of X?',Y.issubset(X))
print('is Y a subset of Z?',Y.issubset(Z))
drawVenn3(X,Y,Z,labels=('X', 'Y', 'Z'))
is Y a subset of X? True is Y a subset of Z? False
A = {3, 9}
B = {5, 9, 1, 3}
print('is A a subset of B?',A.issubset(B))
drawVenn2(A,B)
is A a subset of B? True
A = {3, 3, 3, 9}
B = {5, 9, 1, 3}
print('is A a subset of B?',A<=B)
drawVenn2(A,B)
is A a subset of B? True
A = {1, 2, 3}
B = {2, 3, 4}
print('is A a subset of B?',A.issubset(B))
drawVenn2(A,B)
is A a subset of B? False
Given the universal set $\mathbb{U}$, let $A,B\subseteq \mathbb{U}$, we wrote subset as $A \subseteq B \Leftrightarrow \forall x \left ( x \in A \rightarrow x \in B \right )$
Then, we can define not subset as $A \nsubseteq B \Leftrightarrow \neg \forall x \left ( x \in A \rightarrow x \in B \right )$
From predicate calculus, we know that $\neg \forall x \equiv \exists x \neg$.
Then, we can write not-subset as $A \nsubseteq B \Leftrightarrow \exists x \neg \left ( x \in A \rightarrow x \in B \right )$
From propositional calculus, we know that $ P \rightarrow Q \equiv \neg P \vee Q$
Then, we can write not-subset as $A \nsubseteq B \Leftrightarrow \exists x \neg \left (\neg x \in A \vee x \in B \right )$
From propositional calculus, de Morgan law, we know that $\neg\left ( P \vee Q \right )\equiv \left ( \neg P \wedge \neg Q \right )$
Then, we can write not-subset as $A \nsubseteq B \Leftrightarrow \exists x \left ( x \in A \wedge \neg\left ( x \in B \right ) \right )$
Thus, we have simpler definition of not-subset is $A \nsubseteq B \Leftrightarrow \exists x \left ( x \in A \wedge x \notin B \right )$
A = {1, 2, 3}
B = {2, 3, 4}
print('is A not subset of B?',not A.issubset(B))
is A not subset of B? True
A proper subset is the same as a subset, except that the sets can't be identical.
Suppose A and B are sets. A is a proper subset of B if A is subset of B and there exists at least one element in B that is not in A.
A is a proper subset of B is written matematically as $A \subset B$, defined as
$A \subset B\Leftrightarrow \forall x\left ( x \in A \rightarrow x \in B \right ) \wedge \exists x\left ( x \in B \cap x\notin A \right )$
From predicate calculus, we know that $\exists x \equiv \neg \forall x $, then we can write proper subset equivalently as
$A \subset B\Leftrightarrow \forall x\left ( x \in A \rightarrow x \in B \right ) \wedge \neg \forall x\left ( x \in B \rightarrow x\in A \right )$
Cardinality for finite set: $A \subset B \rightarrow \left | A \right | < \left | B \right |$
Python issubset method contains the equality $A \subseteq B$, it is not proper subset $A \subset B$.
A = {3, 9, 5, 1}
B = {5, 9, 1, 3}
print('is A a subset of B?',A.issubset(B))
drawVenn2(A,B)
is A a subset of B? True
How do we represent "is A a proper subset of B" in Python?
use < operator
A < B returns True if A is a proper subset of B
A = {3, 9, 5, 1}
B = {5, 9, 1, 3}
print('is A a proper subset of B?',A<=B)
is A a proper subset of B? True
Subset operation is transitive. If A is a subset of B and B is a subset of C then A is also a subset of C.
$\left( A \subseteq B \right) \cap \left( B \subseteq C \right) \rightarrow \left( A \subseteq C \right)$
The example and the Venn diagram is show below. The numbers inside the Venn diagram are the number of elements.
A={5,9}
B={1,3,5,7,9}
C={1,2,3,4,5,6,7,8,9}
drawVenn3(A,B,C)
Suppose $A$ and $B$ are sets from a universe $\mathbb{U}$. If $A$ is a subset of $B$, then $B$ is the superset of $A$.
$A \subseteq B \rightarrow B \supseteq A$
How do we represent "is B a superset of A" in Python? Use issuperset() set method
B.issuperset(A)
Alternatively, we can use >= operator
B >= A
or > operator for proper superset
B > A
F={'durian','kiwi','apple', 'banana', 'cherry'}
G={'apple', 'banana', 'cherry'}
drawVenn2(F,G,labels=('F','G'))
print('is F superset of G?',F.issuperset(G))
is F superset of G? True
A = {1, 2, 3}
B = {2, 3, 4}
print('is A a superset of B?', A >= B)
drawVenn2(A,B)
is A a superset of B? False
A={5,9}
B={1,3,5,7,9}
print('is B a superset of A?', B >= A)
drawVenn2(A,B)
is B a superset of A? True
For a given universal set $\mathbb{U}$, two sets are said to be equal if and only if they contain exactly the same elements, regardless the order.
In Python, we can test equality of two sets simply by two equal signs == like the following example.
A = {1, 2, 3}
B = {2, 3, 1}
drawVenn2(A,B)
A==B
True
A = {1, 2, 3, 1, 2}
B = {2, 3, 1}
drawVenn2(A,B)
A==B
True
In connection with subset, we say that set A is equal to set B if and only if A is a subset of B and B is also a subset of A. Two sets A and B are said to be equal if every element of A is an element of B and every element of B is an element of A.
$A=B \Leftrightarrow \left ( A \subseteq B \right ) \wedge \left ( B \subseteq A \right )$
A.issubset(B) & B.issubset(A)
True
If $A$ is a set from the universal set $\mathbb{U}$, the power set $\boldsymbol{\texttt{P}}(A)$ of a set $A$ is the set of all subsets of $A$. If $A$ has $n$ elements in it then $\boldsymbol{\texttt{P}}(A)$ will have $2^n$ elements. Thus, the power set of $A$ is ofen written as $2^A$.
$\boldsymbol{\texttt{P}}(A) = 2^A = \left \{ B | B \subseteq A \right \}$
An empty set is always a subset of set $A$.
To get the power set in Python, we need to list all combinations of the elements of the input set. However, a set of sets is not allowed in Python. Thus, several methods had been proposed to compute power set and they produce the same results. Below are some of them.
# https://www.delftstack.com/howto/python/powerset-python/
# produce list of list
def powerset(A):
listsub = list(A)
subsets = []
for i in range(2**len(listsub)):
subset = []
for k in range(len(listsub)):
if i & 1<<k:
subset.append(listsub[k])
subsets.append(subset)
return subsets
# https://stackoverflow.com/questions/1482308/how-to-get-all-subsets-of-a-set-powerset
# produce set of tuple
from itertools import chain, combinations
def powerset(A):
s = list(A)
return set(chain.from_iterable(combinations(s, r) for r in range(len(s)+1)))
# https://stackoverflow.com/questions/41626379/python-power-set-of-a-list
# produce list of sets
def powerset(A):
if not A: # Empty list -> empty set
return [set()]
r = []
for y in A:
sy = set((y,))
for x in powerset(A - sy):
if x not in r:
r.extend([x, x|sy])
return r
# https://stackoverflow.com/questions/68124242/generating-power-set-with-recursion-and-yield-statement-in-python
# produce list of list, the code is shortest
def powerset(A):
ans = [[]]
for n in A:
ans += [a+[n] for a in ans]
return ans
# A={'a','b','c','d', 'e', 'f', 'g'}
# A={'a','b','c','d'}
# A={'a','b','c'}
# A={'a','b'}
# A={'a'}
A={}
powerset(A)
[[]]
A={'x','y','z'}
powerset(A)
[[], ['y'], ['z'], ['y', 'z'], ['x'], ['y', 'x'], ['z', 'x'], ['y', 'z', 'x']]
X = {'red', 'blue', 'yellow'}
powerset(X)
[[], ['blue'], ['red'], ['blue', 'red'], ['yellow'], ['blue', 'yellow'], ['red', 'yellow'], ['blue', 'red', 'yellow']]
In general, any finite non empty set $A$ with $n$ elements would have $2^n$ subsets. That described as he cardinality of power set $\left | \boldsymbol{\texttt{P}}\left ( x \right ) \right | = 2^n$.
For any $0 \leqslant k \leqslant n$, there are $\binom{n}{k}$ subsets of size $k$.
Counting the subsets of $A$ according to the number, $k$, of elements in a subset, we have combinatorial identity for $n\geq 0$:
$\binom{n}{0} + \binom{n}{1} + \binom{n}{2} + ...+ \binom{n}{n} = \sum_{k=0}^{n} \binom{n}{k} = 2^n$
The cartesian product of two sets will be a set of all possible ordered pairs with the first element of each ordered pair from the first set and the second element from the second set.
The Cartesian product of two sets A and B is defined as the set:
$A \times B = \left \{ \left ( a,b \right ) | a \in A \cap b \in B \right \}$
def cartesianProduct(A,B):
return {(x,y) for x in A for y in B}
A = {'good', 'bad'}
B = {'student', 'prof'}
print(cartesianProduct(A,B))
print(cartesianProduct(B,A))
{('good', 'prof'), ('good', 'student'), ('bad', 'prof'), ('bad', 'student')} {('student', 'bad'), ('prof', 'good'), ('student', 'good'), ('prof', 'bad')}
A = {'x', 'y'}
B = {'a', 'b', 'c'}
print(cartesianProduct(A,B))
print(cartesianProduct(B,A))
{('x', 'b'), ('y', 'a'), ('y', 'c'), ('x', 'a'), ('x', 'c'), ('y', 'b')} {('a', 'x'), ('a', 'y'), ('c', 'x'), ('c', 'y'), ('b', 'x'), ('b', 'y')}
Some properties of Cartesian Products:
A = {'a', 'b', 'c'}
E = {}
print(cartesianProduct(A,E))
print(cartesianProduct(E,A))
set() set()
Let us discuss about the following set operations:
Set union of A and B return the set of all elements in either A or B or both. This is the equivalent to logical operation OR.
$A \cup B = \left ( x \in A \vee x \in B\right )$
Cardinality: $ \left | A \cup B \right | = \left | A \right | + \left | A \right | - \left | A \cap B \right |$
In Python, we can use either union() method or bar | operator.
A.union(B)
A|B
x={'apple', 'banana', 'cherry', 'durian','kiwi'}
y={'durian','kiwi' ,'mango', 'orange','pineaple'}
x|y # set union
{'apple', 'banana', 'cherry', 'durian', 'kiwi', 'mango', 'orange', 'pineaple'}
X = {'a','b','c','d','e'}
Y = {'d','e','f','g'}
print('X|Y =',X|Y)
print('Y|X =',Y|X) # show that union operation is commutative
drawVenn2(X,Y,labels=('X','Y'))
X|Y = {'g', 'd', 'b', 'c', 'f', 'e', 'a'} Y|X = {'g', 'd', 'a', 'b', 'c', 'e', 'f'}
Set intersection return the set of elements common to both A and B. This is the equivalent to logical operation AND.
$A \cap B = \left ( x \in A \wedge x \in B\right )$
In Python, we can use either intersection() method or ampersand & operator.
A.intersection(B)
A & B
X = {'a','b','c','d','e'}
Y = {'d','e','f','g'}
print('X&Y =',X&Y)
print('Y&X =',Y&X) # show that intersection operation is commutative
drawVenn2(X,Y,labels=('X','Y'))
X&Y = {'e', 'd'} Y&X = {'e', 'd'}
Two sets are called disjoint if their intersection is empty, that is, they share no common elements.
$A \cap B = \varnothing$
In Python, we can test whether the two sets are disjoint using isdisjoint() method.
A.isdisjoint(B)
X = {1,2,3,4,}
Y = {6,7,8,9}
print(X.isdisjoint(Y))
drawVenn2(X,Y, labels=('X','Y'))
True
The difference between two sets A and B contains exactly those elements of A that are not in B:
$A - B = \left \{ x | x \in A \wedge x \notin B\right \}$
Cardinality: $ \left | A - B \right | = \left | A \right | - \left | A \cap B \right |$
In Python, we can use either difference() method or minus - operator.
A.difference(B)
A - B
X = {'a','b','c','d','e'}
Y = {'d','e','f','g'}
print('X-Y =',X-Y)
print('Y-X =',Y-X) # show that set difference operation is NOT commutative
drawVenn2(X,Y,labels=('X','Y'))
X-Y = {'c', 'a', 'b'} Y-X = {'g', 'f'}
The complement of a set A contains exactly those elements under consideration that are not in A. This is the equivalent to logical operation NOT.
$A^c=U-A$
U = {1,2,3,4,5,6,7,8,9}
A = {3,4,5}
Ac= U-A
print('~A =',Ac) # this is the complement
print(not A) # be careful: this is not the set compplement but the logical value of the complement
~A = {1, 2, 6, 7, 8, 9} False
E=set()
Ec=U-E
print('~E =',Ec) # this is the complement
print(not E) # be careful: this is not the set compplement but the logical value of the complement
~E = {1, 2, 3, 4, 5, 6, 7, 8, 9} True
X = {'a','b','c','d','e'}
Y = {'d','e','f','g'}
drawVenn2(X,Y,labels=('X','Y'))
U = X.union(Y)
print('U =',U) # this is the universal set
print('~X =',U-X) # this is the complement of X
print('~Y =',U-Y) # this is the complement of Y
print('~(X|Y) =',U-(X|Y)) # this is the complement of the union
print('~(X&Y) =',U-(X&Y)) # this is the complement of the intersection
print('~(X^Y) =',U-(X^Y)) # this is the complement of the symmetric difference
U = {'g', 'd', 'b', 'c', 'f', 'e', 'a'} ~X = {'g', 'f'} ~Y = {'c', 'a', 'b'} ~(X|Y) = set() ~(X&Y) = {'g', 'a', 'b', 'c', 'f'} ~(X^Y) = {'e', 'd'}
Set Symmetric Difference returns the set of all elements in either A or B, but not both. This is the equivalent to logical operation XOR.
In Python, we can use either symmetric_difference() method or caret ^ operator.
A.symmetric_difference(B)
A ^ B
X = {'a','b','c','d','e'}
Y = {'d','e','f','g'}
print('X^Y =',X^Y)
print('Y^X =',Y^X)
drawVenn2(X,Y,labels=('X','Y'))
print('is Y^X = X^Y? ',Y^X==X^Y) # show that set symmetric difference operation is commutative
X^Y = {'g', 'a', 'b', 'c', 'f'} Y^X = {'g', 'c', 'f', 'a', 'b'} is Y^X = X^Y? True
Having the set operations, we can now show the most important set identities.
We will use the following example for all the set identities. You can change the elements on these example sets.
A = {'a','b','c','d','e'}
B = {'d','e','f','g','b'}
C = {'d','h','i','a','f'}
drawVenn3(A,B,C)
E = set()
U = E.union(A,B,C)
print('E=',E)
print('U=',U)
E= set() U= {'g', 'i', 'd', 'b', 'c', 'f', 'e', 'h', 'a'}
$ A \cup \varnothing = A $
$ A \cap \mathbb{U} = A $
print('A|E=',A|E)
print('A&U=',A&U)
print('is A|E==A ?', A|E==A)
print('is A&U==A ?',A&U==A)
A|E= {'c', 'e', 'd', 'a', 'b'} A&U= {'d', 'b', 'c', 'e', 'a'} is A|E==A ? True is A&U==A ? True
$ A \cup \mathbb{U} = \mathbb{U} $
$ A \cap \varnothing =\varnothing $
print('A|U=',A|U)
print('A&E=',A&E)
print('is A|U==U ?', A|U==U)
print('is A&E==E ?',A&E==E)
A|U= {'g', 'i', 'd', 'b', 'c', 'f', 'e', 'h', 'a'} A&E= set() is A|U==U ? True is A&E==E ? True
$ A \cup A = A $
$ A \cap A = A $
print('is A|A==A ?', A|A==A)
print('is A&A==A ?',A&A==A)
is A|A==A ? True is A&A==A ? True
$ \neg \left ( \neg A \right ) = A $
Ac = U-A # A complement
print('A=',A)
print('~A=',Ac)
print('~(~A)=',U-Ac)
print('is ~(~A)==A ?', not (not A)==A)
U-Ac==A
A= {'d', 'b', 'c', 'e', 'a'} ~A= {'g', 'i', 'f', 'h'} ~(~A)= {'d', 'b', 'c', 'e', 'a'} is ~(~A)==A ? True
True
$ A \cup B = B \cup A $
$ A \cap B = B \cap A $
print('is A|B==B|A ?', A|B==B|A)
print('is A&B==B&A ?', A&B==B&A)
is A|B==B|A ? True is A&B==B&A ? True
$ A \cup ( B \cup C) = (A \cup B ) \cup C $
$ A \cap ( B \cap C) = (A \cap B ) \cap C $
print('is A|(B|C)==(A|B)|C ?', A|(B|C)==(A|B)|C)
print('is A&(B&C)==(A&B)&C ?', A&(B&C)==(A&B)&C)
is A|(B|C)==(A|B)|C ? True is A&(B&C)==(A&B)&C ? True
$ A \cap ( B \cup C) = (A \cap B ) \cup (A \cap C ) $
$ A \cup ( B \cap C) = (A \cup B ) \cap (A \cup C ) $
print('is A&(B|C)==(A&B)|(A&C) ?', A&(B|C)==(A&B)|(A&C))
print('is A|(B&C)==(A|B)&(A|C) ?', A|(B&C)==(A|B)&(A|C))
is A&(B|C)==(A&B)|(A&C) ? True is A|(B&C)==(A|B)&(A|C) ? True
$ \neg \left ( A \cup B \right ) = \left ( \neg A \cap \neg B \right ) $
$ \neg \left ( A \cap B \right ) = \left ( \neg A \cup \neg B \right ) $
print('is U-(A|B)==(U-A)&(U-B) ?', U-(A|B)==(U-A)&(U-B))
print('is U-(A&B)==(U-A)|(U-B) ?', U-(A&B)==(U-A)|(U-B))
print('is -(A|B)==(-A)&(-B) ?', not (A|B)==(not A)&(not B)) # this is logical, not set
print('is -(A&B)==(-A)|(-B) ?', not (A&B)==(not A)|(not B)) # this is logical, not set
is U-(A|B)==(U-A)&(U-B) ? True is U-(A&B)==(U-A)|(U-B) ? True is -(A|B)==(-A)&(-B) ? True is -(A&B)==(-A)|(-B) ? True
$ A \cup ( A \cap B) = A $
$ A \cap ( A \cup B) = A $
print('is A|(A&B)==A ?', A|(A&B)==A)
print('is A&(A|B)==A ?', A&(A|B)==A)
is A|(A&B)==A ? True is A&(A|B)==A ? True
$ A \cup \neg A = \mathbb{U} $
$ A \cap \neg A = \varnothing $
$ \neg \varnothing = \mathbb{U} $
$ \neg \mathbb{U} = \varnothing $
print('U =',U)
print('A|Ac =',A|Ac)
print('A&Ac =',A&Ac)
print('is A|Ac==U?',A|Ac==U)
print('is A&Ac==E?',A&Ac==E)
print('is U-E==U?',U-E==U)
print('is U-U==E ?', U-U==E)
U = {'g', 'i', 'd', 'b', 'c', 'f', 'e', 'h', 'a'} A|Ac = {'g', 'i', 'd', 'b', 'c', 'f', 'e', 'h', 'a'} A&Ac = set() is A|Ac==U? True is A&Ac==E? True is U-E==U? True is U-U==E ? True
Set Operations
Cartesian Product
Powerset
Drawing Venn Diagrams in Python
Writing Set notation in Latex:
last update: Aug 2022
Cite this tutorial as: Teknomo.K. (2022) Set Theory in Python http://people.revoledu.com/kardi/tutorial/Python/
See Also: Python for Data Science
Visit people.Revoledu.com for more tutorials in Data Science
Copyright © 2022 Kardi Teknomo
Permission is granted to share this notebook as long as the copyright notice is intact.