Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the coordinates of a cuboid using list comprehension in Python

X, Y and Z are the three coordinates of a cuboid.

Now X=1,Y=1, Z=1 and N=2.

I have to generate a list of all possible coordinates on a 3D grid where the sum of Xi + Yi + Zi is not equal to N. If X=2, the possible values of Xi can be 0, 1 and 2. The same applies to Y and Z.

I have written this below code so far, and it is giving the output as :

[[0, 0, 0]]

however the expected output is

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]

Below is my code, what is going wrong in my code?

[[x,y,z] for x in range(X) for y in range(Y) for z in range(Z) if x+y+z != N]
like image 292
H.Burns Avatar asked Jan 19 '16 09:01

H.Burns


2 Answers

range is actually a half-closed function. So, the ending value will not be included in the resulting range.

If X=2, the possible values of Xi can be 0, 1 and 2

In your code, range(X) will give only 0 and 1, if X is 2. You should have used range(X + 1).

X, Y, Z, N = 1, 1, 1, 2
[[x,y,z] for x in range(X + 1) for y in range(Y + 1) for z in range(Z + 1) if x+y+z != N]

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]

You can write the same, with itertools.product, like this

X, Y, Z, N = 1, 1, 1, 2
from itertools import product
[list(i) for i in product(range(X + 1), range(Y + 1), range(Z + 1)) if sum(i) != N]

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]
like image 78
thefourtheye Avatar answered Sep 28 '22 18:09

thefourtheye


Another approch with itertools.product and list comprehension:

In [91]: [list(l) for l in it.product([0,1], repeat=3) if sum(l) != 2]
Out[91]: [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]
like image 27
Anton Protopopov Avatar answered Sep 28 '22 16:09

Anton Protopopov