How to generate (enumerate) 2**N tuples representing all vertices of unit hypercube in N-dimensional hyperspace ?

Paul Rubin http
Tue Jan 3 20:46:00 EST 2006


Heiko Wundram <modelnine at bit-bukket.org> writes:
> def perm(n):
>     rv = []
>     for i in xrange(2L**n):
>         cur = []
>         for j in range(n):
>             cur.append(1-2*(bool(i & (1<<j))))
>         # cur is in reversed order LSB first, but as you seemingly don't
>         # care about order of the returned tuples, this is irrelevant.
>         rv.append(tuple(cur))
>     return rv

def perm(n):
   return [tuple([(1,-1)[(t>>i)%2] for i in xrange(n)])
              for t in xrange(2L**n)]

>>> perm(4)
[(1, 1, 1, 1), (-1, 1, 1, 1), (1, -1, 1, 1), (-1, -1, 1, 1), (1, 1,
-1, 1), (-1, 1, -1, 1), (1, -1, -1, 1), (-1, -1, -1, 1), (1, 1, 1,
-1), (-1, 1, 1, -1), (1, -1, 1, -1), (-1, -1, 1, -1), (1, 1, -1, -1),
(-1, 1, -1, -1), (1, -1, -1, -1), (-1, -1, -1, -1)]
>>>



More information about the Python-list mailing list