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

bonono at gmail.com bonono at gmail.com
Wed Jan 4 03:28:15 EST 2006


Dr. Colombes wrote:
> 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:
>
> (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?
>
> Thanks for your help.

Is this just a special case for the list of list combine() function
posted not long ago ?

def combine_lol(seq):
    return reduce(lambda x,y: (a+(b,) for a in x for b in y), seq,
[()])

list(combine_lol([(1,-1)]*4))




More information about the Python-list mailing list