唯一排列生成器?
问题:我有一组数字,比如 [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]
,然后把剩下的数字放到不同的位置上。
谢谢大家的帮助,明确一下,我不是想过滤掉重复的排列,而是希望一开始就只生成独特的排列。
1 个回答
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)
我的笔记本电脑用set(permutations(seq))
这个方法处理长度为11的输入序列时会卡,但用这个方法就没问题了!