Permutations with repetition in Python

后端 未结 5 1281
囚心锁ツ
囚心锁ツ 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:56

    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)]
    

提交回复
热议问题