I understand that any python set union
with empty set would result in itself. But some strange behave I detect when union
is inside of a for loop.
num= set([2,3,4]) emp= set() print num|emp >>>set([2, 3, 4])
s = set() inp = ["dr101-mr99","mr99-out00","dr101-out00","scout1-scout2","scout3- scout1","scout1-scout4","scout4-sscout","sscout-super"] for ele in inp: r = set(ele.split("-")) print r s.union(r) print s >>>set(['mr99', 'dr101']) set(['out00', 'mr99']) set(['out00', 'dr101']) set(['scout1', 'scout2']) set(['scout1', 'scout3']) set(['scout4', 'scout1']) set(['scout4', 'sscout']) set(['super', 'sscout']) set([])
anyone could tell me why the last set s is empty? is the output supposed to be every unique element in the set?
The union of two sets is a set containing all elements that are in A or in B (possibly both). For example, {1,2}∪{2,3}={1,2,3}. Thus, we can write x∈(A∪B) if and only if (x∈A) or (x∈B). Note that A∪B=B∪A.
The intersection of two sets A and B ( denoted by A∩B ) is the set of all elements that is common to both A and B. In mathematical form, For two sets A and B, A∩B = { x: x∈A and x∈B } Similarly for three sets A, B and C, A∩B∩C = { x: x∈A and x∈B and x∈C }
To find the union of two sets, we take X and Y, which contains all the elements of X and all the elements of Y such that no element is repeated. The symbol for representing the union of sets is '∪'.
Formula for Probability of Union of 4 Sets Given four sets A, B, C and D, the formula for the union of these sets is as follows: P (A U B U C U D) = P(A) + P(B) + P(C) +P(D) - P(A ∩ B) - P(A ∩ C) - P(A ∩ D)- P(B ∩ C) - P(B ∩ D) - P(C ∩ D) + P(A ∩ B ∩ C) + P(A ∩ B ∩ D) + P(A ∩ C ∩ D) + P(B ∩ C ∩ D) - P(A ∩ B ∩ C ∩ D).
s.union(r)
is a new set with elements from both s
and r
.reference You need to change
s.union(r)
to
s = s.union(r)
or, use set.update
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With