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.
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)]
[tuple(sign * (i == p) for i in range(n)) for p in range(n) for sign in (-1, 1)]
Plain for
, no implicit bool
→int
equivalent:
for p in range(n):
for sign in (-1, 1):
yield tuple((sign if i == p else 0) for i in range(n))
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With