permutations with unique values

前端 未结 19 1430
爱一瞬间的悲伤
爱一瞬间的悲伤 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:34

    This is my attempt without resorting to set / dict, as a generator using recursion, but using string as input. Output is also ordered in natural order:

    def perm_helper(head: str, tail: str):
        if len(tail) == 0:
            yield head
        else:
            last_c = None
            for index, c in enumerate(tail):
                if last_c != c:
                    last_c = c
                    yield from perm_helper(
                        head + c, tail[:index] + tail[index + 1:]
                    )
    
    
    def perm_generator(word):
        yield from perm_helper("", sorted(word))
    

    example:

    from itertools import takewhile
    word = "POOL"
    list(takewhile(lambda w: w != word, (x for x in perm_generator(word))))
    # output
    # ['LOOP', 'LOPO', 'LPOO', 'OLOP', 'OLPO', 'OOLP', 'OOPL', 'OPLO', 'OPOL', 'PLOO', 'POLO']
    

提交回复
热议问题