6

I'm trying to get the coordinates of an n-dimensional cube from a list of the mins and maxes for each dimension. I'm able to get the corners using for loops but I would like to generalize for any number of dimensions.

So for instance:

mins = [-1,-2,-3]
maxes = [1,2,3]

would give the coordinates:

(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3),
(1, 2, 3), (1, 2, -3), (1, -2, 3), (1, -2, -3)

This is essentially finding all the paths through two lists, choosing a value from one of the lists for each index. I've seen algorithms to give the number of paths or the fastest path, but I haven't found one that enumerates all of the possible paths.

I'd assume itertools would come into the solution, but cannot figure out how to use products, permutations, and combinations in way that gives the desired result. The closest has been:

list(itertools.product((xmin, xmax), (ymin, ymax), (zmin, zmax)))
David Alber
  • 17,624
  • 6
  • 65
  • 71
  • 1
    Does the order matter? If not your "closest solution" should be correct, and identical to [Jochen's answer](http://stackoverflow.com/questions/8058491/python-corner-coordinates-of-n-dimensional-cube/8058593#8058593). – Andrew Clark Nov 08 '11 at 23:49
  • The order is not important. Thank you. What is the * operator in front of zip do? –  Nov 09 '11 at 00:07
  • The term the docs uses for the `*` operator (as used here) is [unpacking argument lists](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists). Basic summary is that `func(*[a, b, c])` is equivalent to `func(a, b, c)` (any iterable can be used, not just lists). – Andrew Clark Nov 09 '11 at 00:31

1 Answers1

12

You were pretty close, *zip( ... ) is what you were looking for:

>>> list(itertools.product(*zip([-1,-2,-3],[1,2,3])))
[(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (
, 2, -3), (1, 2, 3)]
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
  • Wow, thanks for the response. I just found another solution, but this one seems much easier to understand. –  Nov 09 '11 at 00:00
  • def perm(n, mins, maxes): return [tuple([(mins[i], maxes[i])[(t >> i) % 2] for i in xrange(n)]) for t in xrange(2L ** n)] –  Nov 09 '11 at 00:02