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

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

    Here is my implementation:

    a = [1,2,3,4]
    
    def p(l):
      if len(l) <= 1:
        yield l
      else:
        for i in range(len(l)):
          for q in p([l[j] for j in range(len(l)) if j != i]):
            yield [l[i]] + q
    
    out = (i for i in p(a) if i < i[::-1])
    

    P function is a regular permu function, yields all possibilities. The filter is done when iterates the result. Simply, it has two possible results, the smaller half of the all permus and the bigger half of the permus. In this example, the out contains the smaller half of the list.

提交回复
热议问题