demon.mhm
demon.mhm

Reputation: 469

python coordinates generator

I need to generate all points coordinates by given dimensions, for example:

>>>points(2,2)
>>>[(0,0),(0,1),(1,0),(1,1)]
>>>points(1,1,1)
>>>[(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,1,0),(1,1,1)]

I,ve seen solution for 2-dimensions, but cant find a way to make method independent of number of dimensions:

>>> from itertools import product
>>> list(product(xrange(d) for d in (1,2,3)))
[(xrange(1),), (xrange(2),), (xrange(3),)] #where is my tuples?

where (1,2,3) are *args tuple, which can be anything.

Upvotes: 1

Views: 385

Answers (1)

svk
svk

Reputation: 5919

You need to use a * when calling the function to use an iterable object as an argument list. f(*[1,2,3]) works like f(1,2,3).

Knowing this, and using itertools:

def points(*args):
  return list(product(*[range(n) for n in args]))

Upvotes: 2

Related Questions