A list comprehension returns wrong result

list-comprehension, python

Solution

You are using the wrong operator. You want boolean `and`; `&` is a bitwise operator:

[(i,j,k) for (i,j,k) in [(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)) ]  ]

You can eliminate that nested list comprehension, it is redundant:

[(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))]

Next, use the `itertools.product()` function to generate all combinations instead of nested loops, and `all()` to test if all values are non-zero:

from itertools import product
[t for t in product({-4,-2,1,2,5,0}, repeat=3) if sum(t) > 0 and all(t)]

but you may as well omit the `0` from the set and save yourself the `all()` test:

from itertools import product
[t for t in product({-4,-2,1,2,5}, repeat=3) if sum(t) > 0]

and perhaps you wanted to correct that test to equals to 0:

from itertools import product
[t for t in product({-4,-2,1,2,5}, repeat=3) if sum(t) == 0]

Result:

>>> [t for t in product({-4,-2,1,2,5}, repeat=3) if sum(t) == 0]
[(1, 1, -2), (1, -2, 1), (2, 2, -4), (2, -4, 2), (-4, 2, 2), (-2, 1, 1)]

Problem

I've been searching all over but wasn't able to fig this thing out. I'm from a Java background, if that helps, trying to learn python. ``` a = [ (i,j,k) for (i,j,k) in [ (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 & (i!=0 & j!=0 & k!=0)) ] ] ``` Statement is : get all the tuples whose sum is zero, but none of them should have 0 in it. Always, this results consists of all tuples. :(

Original source