Find cuboid coordinates using list comprehension in Python

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

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

I need to generate a list of all possible coordinates on a three-dimensional grid, where the sum of Xi + Yi + Zi is not equal to N. If X = 2, then the possible values โ€‹โ€‹of Xi can be 0, 1 and 2. The same applies to Y and Z.

I have written this code so far, and it gives the result as:

 [[0, 0, 0]] 

however expected result

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

Below is my code, what is 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] 
+6
source share
4 answers

range is actually a semi-closed function. Thus, the final 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 only return 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 thing 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]] 
+8
source

Another approach 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]] 
+1
source

try the following:

  x = int(input()) y = int(input()) z = int(input()) n = int(input()) ans=[[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if i+j+k !=n] print(ans) 

since the range function does not include the final value and is stopped at the (n-1) -th position, therefore, if we use the range (X), here it will only lead to 0, therefore +1 should be used to print the list in lexicographic increase order .

0
source
 x = int(input()) y = int(input()) z = int(input()) n = int(input()) result = [] for i in range(x+1): for j in range(y+1): for k in range(z+1): if((x+y+z) != 1): arr = [i,j,k] result.append(arr) print(result) 
0
source

Source: https://habr.com/ru/post/1240907/


All Articles