简体   繁体   中英

Code for generating all unique permutations recursively?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM