Skip to content Skip to sidebar Skip to footer

Unique Permutation Generator?

The problem: I have some list of numbers, like [1,1,2]. I need to generate the unique permutations. The permutations are [1,1,2],[1,1,2],[1,2,1],[1,2,1],[2,1,1],[2,1,1]. I need to

Solution 1:

I adapted this code from a previous Stack Overflow answer:

defdistinct_permutations(seq):
  from collections import Counter

  defperm_unique_helper(item_counts, perm, i):
    if i < 0:
      yieldtuple(perm)
    else:
      for item in item_counts:
        if item_counts[item] <= 0:
          continue
        perm[i] = item
        item_counts[item] -= 1# In Python < 3.3 you can replace the yield from with a loopyieldfrom perm_unique_helper(item_counts, perm, i - 1)
        item_counts[item] += 1

  item_counts = Counter(seq)
  L = len(seq)

  return perm_unique_helper(item_counts, [0] * L, L - 1)

My laptop can't do length-11 input sequences with the set(permutations(seq)) method, but with this method it can!

Post a Comment for "Unique Permutation Generator?"