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

Paul Rubin http
Tue Jan 3 20:32:38 EST 2006

```"Dr. Colombes" <DrColombes at yahoo.com> writes:
> I'm looking for a good Python way to generate (enumerate) the 2**N
> tuples representing all vertices of the unit hypercube in N-dimensional
> hyperspace.
> For example, for N=4 the Python code should generate the following 2**N
> = 16 tuples:

Here's a recursive generator:

def hypercube(ndims):
if ndims == 0:
yield ()
return
for h in 1, -1:
for y in hypercube(ndims-1):
return (h,)+y

>>> print list(hypercube(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)]
>>>

> 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?

Yeah you could do that too.

```