Code for generating all unique permutations recursively?

走远了吗. 提交于 2019-12-24 11:23:41

问题


Say I have a list L=[1,2,3,3,4] and I want to find all permutations of length 3 recursively.

I am trying to return all unique permutations, which means something like [1,2,3] isn't included in the output twice because there are two 3's in L.

I ask because itertools.permutations includes duplicates, and also I am trying to iterate through the permutations in order (iterating from the lowest [1,2,3] up to [4,3,3]) because I want to be able to quit iterating whenever I need to.

I'm sorry if I haven't explained things properly.

Edit: I should probably elaborate again. In practice, I don't want to actually generate every single possible permutation (there would be way too many), although the code could if it ran to completion. I'm trying to iterate through all the permutations in a particular order so that I can bail early if necessary.


回答1:


How about this:

l = [1,2,3,3,4]

print sorted(set(itertools.permutations(l,3)))

Output:

[(1, 2, 3), (1, 2, 4), (1, 3, 2), (1, 3, 3), (1, 3, 4), ..., (4, 3, 3)]

This keeps it in order and removes duplicates.


If you want to avoid generating each possible permutation before-hand, I would do something like this:

gen = itertools.permutations(l,3)
s = set()

for i in gen:
    if i not in s:
        print i  # or do anything else
    # if some_cond: break
    s.add(i)

Here gen is a generator, so you are not pre-creating all of the elements you might use.



来源:https://stackoverflow.com/questions/13408213/code-for-generating-all-unique-permutations-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!