Permutations with repetition in Python

后端 未结 5 1284
囚心锁ツ
囚心锁ツ 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 04:01

    If you've written more than eight lines of code to generate eight constant values, something has gone wrong.

    Short of just embedding the list I want, I'd do it the dumb way:

    vertices = (
        (v.count(1), v)
        for v in itertools.product((0, 1), repeat=3)
    )
    for count, vertex in sorted(vertices):
        print vertex
    

    Unless you're working with 1000-hypercubes, you shouldn't have any huge performance worries.

提交回复
热议问题