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:
&
An (inefficient) alternative method:
>>> ['{0:03b}'.format(x) for x in range(8)]
['000', '001', '010', '011', '100', '101', '110', '111']
Or as tuples:
>>> [tuple(int(j) for j in list('{0:03b}'.format(x))) for x in range(8)]
[(0, 0, 0),
(0, 0, 1),
(0, 1, 0),
(0, 1, 1),
(1, 0, 0),
(1, 0, 1),
(1, 1, 0),
(1, 1, 1)]
Sorted by number of vertices:
>>> sorted(_, key=lambda x: sum(x))
[(0, 0, 0),
(0, 0, 1),
(0, 1, 0),
(1, 0, 0),
(0, 1, 1),
(1, 0, 1),
(1, 1, 0),
(1, 1, 1)]
Or using itertools:
>>> sorted(itertools.product((0, 1), repeat=3), key=lambda x: sum(x))
[(0, 0, 0),
(0, 0, 1),
(0, 1, 0),
(1, 0, 0),
(0, 1, 1),
(1, 0, 1),
(1, 1, 0),
(1, 1, 1)]