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

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

    This is a more concise and faster version of ChristopheD's accepted answer, which I liked a lot. Recursion is great. I made it enforce uniquenss of the incoming list by removing duplicates, however maybe it should just raise an exception instead.

    def fac(x): 
        return (1 if x==0 else x * fac(x-1))
    
    def permz(plist):
        plist = sorted(set(plist))
        plen = len(plist)
        limit = fac(plen) / 2
        counter = 0
        if plen==1:
            yield plist
        else:
            for perm in permz(plist[1:]):
                for i in xrange(plen):
                    if counter == limit:
                         raise StopIteration
                    counter += 1
                    yield perm[:i] + plist[0:1] + perm[i:]
    
    # ---- testing ----
    plists = [
        list('love'),
        range(5),
        [1,4,2,3,9],
        ['a',2,2.1],
        range(8)]               
    
    for plist in plists:
        perms = list(permz(plist))
        print plist, True in [(list(reversed(i)) in foo) for i in perms]
    

提交回复
热议问题