说我有这个清单: [1,1,2,2] 我想贯穿其中的所有排列。 如果我打印相同的排列将打印4次。 对于[1,1,1,3]同一个将被打印6次, 对于[1,1,1,3,3] 12。
一般情况:(a1)!(a2)! ...(an)! 是否有任何函数在Python中执行此操作? 如果不是,你能给我一个用Python做的算法吗?
答案 0 :(得分:0)
您正在寻找以下内容吗?
import math
def repeats(nums):
counts = dict()
result = 1
for n in nums:
if n in counts:
counts[n] += 1
else:
counts[n] = 1
for n in counts.keys():
result *= math.factorial(counts[n])
return result
print repeats([1, 1, 2, 2]) # prints 4
print repeats([1, 1, 1, 3]) # prints 6
print repeats([1, 1, 1, 3, 3]) # prints 12