I am studying Python
with the aim of becoming an AI human resource, but since the set type content was the content of a set of numbers A, I thought that I would use it in the future, so I will summarize it.
I am using this to study Python. Learning roadmap for Python beginners [You can also study by yourself on your blog]
Set operation with Python, set type (union, intersection and subset judgment, etc.)
--A mass of elements that are not duplicated, have no order, and have no number defined. ――It feels like a relative of a sequence type (string, tuple, list) -Define by separating with commas in {} --Define by changing the data type to a set type (set type) with the set () function
Suppose there are two aggregate types a and b.
--Sets common to a and b (intersection): ʻa & b --A set (difference set) excluding "elements common to a and b (product set)" from a: ʻa --b
--A set (difference set) excluding "elements common to a and b (product set)" from b: b --a
Is the image of the figure below.
--A set (union) that combines all the elements of a and b: ʻa | b`
Is the image of the figure below
-A set that combines "things that belong to a and not belong to b" and "things that belong to b and do not belong to a" (symmetric difference set): ʻa ^ b`
Is the image of the figure below
Let's actually express what was illustrated earlier in code.
set.py
#Define aggregate types a and b
a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
b = {2, 4, 6, 8, 10, 12}
#Intersection
print(a & b) #Execution result:{2, 4, 6, 8, 10}
#Difference set
print(a - b) #Execution result:{1, 3, 5, 7, 9}
print(b - a) #Execution result:{12}
#Union
print(a | b) #Execution result:{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12}
#Symmetric set
print(a ^ b) #Execution result:{1, 3, 5, 7, 9, 12}
By the way, methods can also be used for collective operations.
set.py
#Define aggregate types a and b
a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
b = {2, 4, 6, 8, 10, 12}
#Intersection
print(a & b) #Execution result:{2, 4, 6, 8, 10}
print(a.intersection(b)) #Execution result:{2, 4, 6, 8, 10}
#Difference set
print(a - b) #Execution result:{1, 3, 5, 7, 9}
print(a.difference(b)) #Execution result:{1, 3, 5, 7, 9}
print(b - a) #Execution result:{12}
print(b.difference(a)) #Execution result:{12}
#Union
print(a | b) #Execution result:{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12}
print(a.union(b)) #Execution result:{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12}
#Symmetric set
print(a ^ b) #Execution result:{1, 3, 5, 7, 9, 12}
print(a.symmetric_difference(b)) #Execution result:{1, 3, 5, 7, 9, 12}
I think I'll summarize the subsets in another article. After all, it is recommended to output something because you can organize your mind.
Python is fun!
Recommended Posts