permutations with unique values

前端 未结 19 1423
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 01:53

itertools.permutations generates where its elements are treated as unique based on their position, not on their value. So basically I want to avoid duplicates like this:

相关标签:
19条回答
  • 2020-11-22 02:48

    This relies on the implementation detail that any permutation of a sorted iterable are in sorted order unless they are duplicates of prior permutations.

    from itertools import permutations
    
    def unique_permutations(iterable, r=None):
        previous = tuple()
        for p in permutations(sorted(iterable), r):
            if p > previous:
                previous = p
                yield p
    
    for p in unique_permutations('cabcab', 2):
        print p
    

    gives

    ('a', 'a')
    ('a', 'b')
    ('a', 'c')
    ('b', 'a')
    ('b', 'b')
    ('b', 'c')
    ('c', 'a')
    ('c', 'b')
    ('c', 'c')
    
    0 讨论(0)
提交回复
热议问题