+ 2
Output Confusion
x = {1|2}|{1}|{2} print(x) How does this output {1,2,3} I think the out put should be {1,2}
3 ответов
+ 7
1|2, it uses a bitwise operator OR.
In binary code:
1 = 1 (to make it the same length, 01)
2 = 10
Where 0 is False, 1 is True.
It compares each bit.
01
or
10
From left to right, 0 or 1 equals 1; 1 or 0 equals 1. So it becomes 11.
11 is representing 3. (Try print(bin(3)) in playground, just ignore '0b'.)
Now x = {1|2}|{1}|{2} becomes:
x = {3} | {1} | {2} >> x = {3} union {1} union {2}
x = {1, 2, 3}
+ 1
output - {1,2,3} is correct!
to understand better you can study about bit wise operators by solo learn community course
+ 1
Umer ,
That's a good one. I had to think about it.
It uses two different syntactical meanings of the | symbol.
Inside the first set, | is used as the bitwise-or operator, giving the first set the value {3}.
Between sets, | is used as the union-of-sets operator. Your three sets have the unique values, {3}, {1}, and {2}, resulting in the set that is their union, {3, 1, 2}, being assigned to x.
When a set is printed, the order is not guaranteed and is implementation dependent. This implementation (Sololearn uses CPython) chose to print x in the order {1, 2, 3}.
https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types
https://docs.python.org/3/library/stdtypes.html?highlight=union#set