独特的置换生成器?

Dan*_*dux 4 python algorithm permutation

问题:我有一些数字列表,例如[1,1,2]. 我需要生成唯一的排列。排列是[1,1,2],[1,1,2],[1,2,1],[1,2,1],[2,1,1],[2,1,1]。我只需要生成唯一的排列,即[1,1,2],[1,2,1],[2,1,1].

我的尝试:我的第一次尝试是保留一组现有的排列,并为itertools.permutations生成器创建一个过滤器,该过滤器将使用该组过滤掉重复项。但是,出于效率原因,我宁愿不首先生成这些排列。即使对于 12 个数字的小列表,也只有 1% 是唯一的。

我有一个我似乎无法完全弄清楚的想法的开始:我可以在我的列表中创建唯一值的排列,即[1,2],将剩余的数字放在所有不同的地方。

感谢您的帮助,并且要明确的是,我不想过滤掉重复的排列,我只想首先生成唯一的排列。

bba*_*les 5

我从之前的 Stack Overflow 回答中改编了这段代码:

def distinct_permutations(seq):
  from collections import Counter

  def perm_unique_helper(item_counts, perm, i):
    if i < 0:
      yield tuple(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 loop
        yield from 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)
Run Code Online (Sandbox Code Playgroud)

我的笔记本电脑不能set(permutations(seq))用这个方法做长度为 11 的输入序列,但是用这个方法它可以!