Permutations with repetition in Python

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

    It is not a bad idea to count depending on what you will do with the vertices because if you have to iterate over all of them doing something O(f(n)) is at least O(f(n)*2n), sorting them is O(n*2n). So it basically depends if f(n) majors n.

    Aside from that here is a possible magic expression:

    def magic_expression(ones, n):
        a = (0,) * (n - ones) + (1,) * ones
        previous = tuple()
        for p in itertools.permutations(a):
            if p > previous:
                previous = p
                yield p
    

    With help from permutations with unique values.

    This works because itertools.permutations yield sorted results. Note that a is initially sorted because zeros come first.

提交回复
热议问题