Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly union with set

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.

looks good

num= set([2,3,4]) emp= set() print num|emp >>>set([2, 3, 4]) 

confused

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?

like image 307
lcs Avatar asked Aug 07 '15 16:08

lcs


People also ask

How do you do the union of a 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.

What is a ∩ B ∩ C?

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 }

How do you find the union of a set of numbers?

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 '∪'.

What is the union of 4 sets?

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).


Video Answer


1 Answers

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.

like image 70
Yu Hao Avatar answered Oct 02 '22 16:10

Yu Hao