3 ms·
when you pipe a set it's the same thing as calling union on each one, it creates a new set and puts all the variables in them: so this: border = north | sou
by dec0dedab0de 5y ago
when you pipe a set it's the same thing as calling union on each one, it creates a new set and puts all the variables in them:
so this:
border = north | south | west | east
is the same thing as:
border = north.union(south, west, east)
which is also:
border = set()
for border_set in [north, south, west, east]:
for state in border_set:
border.add(state)
it's just a new set with all the previous items in it. Since it's a set there is no doubles. for example, WA is in north and east, but only in border once, because there is no duplicates in a set.
to do it with lists you would need to make sure there was no doubles yourself. plus you wouldn't get the set operations later on, and would need similar loops to check things.
border = []
for state in north + south + west + east:
if state not in border:
border.append(state)
Sets are great any time you need to work with groups of unique things and see how they relate to each other. Since there is only one of each state, this is perfect use for them.
edits throughout as I thought of other things.
- wodenokoto 5y agoI’ve never thought of that operation as shell pipes, but always as an “or” operator.
- dec0dedab0de 5y agoI just call the character a pipe, It's actually a "bitwise or". i think the reasoning is that it looks at each item in the two sets being compared and returns it if it is in either or both of the sets. Which functionally is the same thing as creating a union. I usually avoid using bitwise operators because they get confusing, and the kind of stuff my team does rarely needs them. In this case I would have used union. edit: here are some of the docs Bitwise operators: https://wiki.python.org/moin/BitwiseOperators https://wiki.python.org/moin/BitwiseOperators and how they work with sets: https://docs.python.org/3.10/tutorial/datastructures.html#sets https://docs.python.org/3.10/tutorial/datastructures.html#se... Plus the set docs have the methods with their corresponding operator: https://docs.python.org/3.10/library/stdtypes.html#set https://docs.python.org/3.10/library/stdtypes.html#set I can see how it would be nice and concise, but I think the methods are easier to understand.
- Snarwin 5y agoGiven two binary numbers a and b, the set of bits set to 1 in a|b is the union of the set of bits set to 1 in a and the set of bits set to 1 in b. Likewise for & (bitwise and) and intersection. So using bitwise operators to represent set operations like this is not too big of a stretch.