I want to iterate over all the vertices of an n
dimensional cube of size 1. I know I could do that with itertools.product
as follows:
&
It is not a bad idea to count depending on what you will do with the vertices because if you have to iterate over all of them doing something O(f(n)) is at least O(f(n)*2n), sorting them is O(n*2n). So it basically depends if f(n) majors n.
Aside from that here is a possible magic expression:
def magic_expression(ones, n):
a = (0,) * (n - ones) + (1,) * ones
previous = tuple()
for p in itertools.permutations(a):
if p > previous:
previous = p
yield p
With help from permutations with unique values.
This works because itertools.permutations yield sorted results. Note that a is initially sorted because zeros come first.