How to generate permutations of a list without “reverse duplicates” in Python using generators

后端 未结 10 1117
情歌与酒
情歌与酒 2020-12-03 12:09

This is related to question How to generate all permutations of a list in Python

How to generate all permutations that match following criteria: if

10条回答
  •  伪装坚强ぢ
    2020-12-03 12:29

    this is an implementation of onebyone's suggestion

    from http://en.wikipedia.org/wiki/Permutation#Lexicographical_order_generation The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place.

    1. Find the highest index i such that s[i] < s[i+1]. If no such index exists, the permutation is the last permutation.
    2. Find the highest index j > i such that s[j] > s[i]. Such a j must exist, since i+1 is such an index.
    3. Swap s[i] with s[j].
    4. Reverse all the order of all of the elements after index i

    the function:

    def perms(items):
        items.sort()
        yield items[:]
        m = [len(items)-2]  # step 1
        while m:
            i = m[-1]
            j = [ j for j in range(i+1,len(items)) if items[j]>items[i] ][-1] # step 2
            items[i], items[j] = items[j], items[i] # step 3
            items[i+1:] = list(reversed(items[i+1:])) # step 4
            if items

    checking our work:

    >>> foo=list(perms([1,3,2,4,5]))
    >>> True in [(list(reversed(i)) in foo) for i in foo]
    False
    

提交回复
热议问题