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

后端 未结 10 1164
情歌与酒
情歌与酒 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:51

    Some setup code first:

    try:
        from itertools import permutations
    except ImportError:
        # straight from http://docs.python.org/library/itertools.html#itertools.permutations
        def permutations(iterable, r=None):
            # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
            # permutations(range(3)) --> 012 021 102 120 201 210
            pool = tuple(iterable)
            n = len(pool)
            r = n if r is None else r
            if r > n:
                return
            indices = range(n)
            cycles = range(n, n-r, -1)
            yield tuple(pool[i] for i in indices[:r])
            while n:
                for i in reversed(range(r)):
                    cycles[i] -= 1
                    if cycles[i] == 0:
                        indices[i:] = indices[i+1:] + indices[i:i+1]
                        cycles[i] = n - i
                    else:
                        j = cycles[i]
                        indices[i], indices[-j] = indices[-j], indices[i]
                        yield tuple(pool[i] for i in indices[:r])
                        break
                else:
                    return
    
    def non_reversed_permutations(iterable):
        "Return non-reversed permutations for an iterable with unique items"
        for permutation in permutations(iterable):
            if permutation[0] < permutation[-1]:
                yield permutation
    

提交回复
热议问题