Reputation: 2830
Given a cube with the coordinates from (-x, -x, -x, ...) to (+y, +y +y, ...), x,y>0, how do I get a list of all integers with short and easy to read code?
So far I have:
list((x,y,z) for x in range(-x,y) for y in range(-x,y) for z in range(-x,y))
# has the dimension hardcoded
list(itertools.product(*[np.arange(-x, y)]*dim))
# difficult to understand what is going on
Is there a more intuitive solution?
Upvotes: 3
Views: 477
Reputation: 28606
Your second solution seems perfectly fine, though I'd do it this way instead:
list(itertools.product(range(-x, y), repeat=dim))
Upvotes: 5
Reputation: 60994
Just encapsulate your "hardcoded" version in a function, and pass the dimensions as arguments
def cube_points(x1, x2, y1, y2, z1, z2): #This describes any rectangular prism
return [(x,y,z) for x in range(x1, x2+1) for y in range(y1, y2+1) for z in range(z1, z2+1)]
Where x1
and x2
are the endpoints of the line formed by projecting the cube onto the x axis, etc.
EDIT: For an n-dimensional cube
from itertools import product
def ndcube(*args): #accepts a list of 2-tuples
return list(product(*map(lambda x: range(x[0], x[1]+1), args)))
Upvotes: 1