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:
&
For your use-case of 3d cubes, Eevee's solution is the correct one.
However for fun and to demonstrate the power of itertools, here's a linear-time solution that generalizes to higher dimensions:
from itertools import combinations
# n is the number of dimensions of the cube (3 for a 3d cube)
def generate_vertices(n):
for number_of_ones in xrange(0, n + 1):
for location_of_ones in combinations(xrange(0, n), number_of_ones):
result = [0] * n
for location in location_of_ones:
result[location] = 1
yield result
for vertex in generate_vertices(3):
print vertex
# result:
# [0, 0, 0]
# [1, 0, 0]
# [0, 1, 0]
# [0, 0, 1]
# [1, 1, 0]
# [1, 0, 1]
# [0, 1, 1]
# [1, 1, 1]