How to generate (enumerate) 2**N tuples representing all vertices of unit hypercube in N-dimensional hyperspace ?
Heiko Wundram
modelnine at bit-bukket.org
Tue Jan 3 20:39:06 EST 2006
Dr. Colombes wrote:
> Maybe converting each integer in the range(2**N) to binary, then
> converting to bit string, then applying the "tuple" function to each
> bit string?
A direct translation of that:
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
modelnine at phoenix ~ $ python
Python 2.4.2 (#1, Dec 22 2005, 17:27:39)
[GCC 4.0.2 (Gentoo 4.0.2-r2, pie-8.7.8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test1 import perm
>>> perm(5)
[(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, 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, -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)]
>>>
modelnine at phoenix ~ $
--- Heiko.
More information about the Python-list
mailing list