简体   繁体   中英

How does Python handle equality checking?

>>> l=[(i,j,k) for i in {-4,-2,1,2,5,0} for j in {-4,-2,1,2,5,0} for k in {-4,-2,1,2,5,0} if i+j+k==0 if i==0 & j==0 & k==0]
>>> l
[(0, 0, 0), (0, 2, -2), (0, -2, 2)]

The above Python 3 code finds triples(i,j,k) such that i+j+k=0 and all elements are 0.So the answer should be (0,0,0).

But the answer came was [(0, 0, 0), (0, 2, -2), (0, -2, 2)]

After a bit of searching I found that the problem lies in the use of & instead of and .I understand that and is a logical operator and & is a bitwise operator.

But I'm not able to figure out why I got the answers I got by using & .

How does Python3 handle equality checking operation?

Your spacing in

i==0 & j==0 & k==0

is misleading you; == has lower precedence than & so the calculation is actually

i == 0&j == 0&k == 0

Because 0&anything is 0, this becomes

i == 0 == 0 == 0

which is the same as

i == 0

because Python chains comparisons (such as 4 < x < 10 ).

Therefore

[(i,j,k) for i in {-4,-2,1,2,5,0} for j in {-4,-2,1,2,5,0} for k in {-4,-2,1,2,5,0} if i+j+k==0 if i==0 & j==0 & k==0]

will give every (i,j,k) tuple where i+j+k = 0 and i = 0 , so where i = 0 and j = -k .

Remove this: if i==0 & j==0 & k==0 .

Solution:

>>> l=[(i,j,k) for i in {-4,-2,1,2,5,0} for j in {-4,-2,1,2,5,0} for k in {-4,-2,1,2,5,0} if i+j+k==0 and (i==0 and j==0 and k==0)]
>>> l
[(0, 0, 0)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM