Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the pythonic way of generating this type of list? (Faces of an n-cube)

if n == 1: return [(-1,),    (1,)]
if n == 2: return [(-1,0),   (1,0),   (0,-1),   (0,1)]
if n == 3: return [(-1,0,0), (1,0,0), (0,-1,0), (0,1,0), (0,0,-1), (0,0,1)]

Basically, return a list of 2n tuples conforming to the above specification. The above code works fine for my purposes but I'd like to see a function that works for all n ∈ ℕ (just for edification). Including tuple([0]*n) in the answer is acceptable by me.

I'm using this to generate the direction of faces for a measure polytope. For all directions, I can use list(itertools.product(*[(0, -1, 1)]*n)), but I can't come up with something quite so concise for only the face directions.

like image 500
rhombidodecahedron Avatar asked Aug 07 '13 15:08

rhombidodecahedron


3 Answers

def faces(n):
    def iter_faces():
        f = [0] * n
        for i in range(n):
            for x in (-1, 1):
                f[i] = x
                yield tuple(f)
            f[i] = 0
    return list(iter_faces())

>>> faces(1)
[(-1,), (1,)]
>>> faces(2)
[(-1, 0), (1, 0), (0, -1), (0, 1)]
>>> faces(3)
[(-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)]
like image 139
falsetru Avatar answered Nov 09 '22 21:11

falsetru


[tuple(sign * (i == p) for i in range(n)) for p in range(n) for sign in (-1, 1)]

Plain for, no implicit boolint equivalent:

for p in range(n):
    for sign in (-1, 1):
        yield tuple((sign if i == p else 0) for i in range(n))
like image 3
Pavel Anossov Avatar answered Nov 09 '22 21:11

Pavel Anossov


The way I am seeing this problem is two simultaneous interleaving n sized shift registers

>>> def shift_register(n):
    l1 = (-1,) + (0,)*(n - 1)
    l2 = (1,) +  (0,)*(n - 1)
    while any(l1):
        yield l1
        yield l2
        l1 = (0,) + l1[:-1]
        l2 = (0,) + l2[:-1]


>>> list(shift_register(3))
[(-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)]
like image 3
Abhijit Avatar answered Nov 09 '22 21:11

Abhijit