Permutations with repetition in Python

后端 未结 5 1283
囚心锁ツ
囚心锁ツ 2021-02-10 03:47

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:

&         


        
5条回答
  •  孤独总比滥情好
    2021-02-10 03:52

    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]
    

提交回复
热议问题