【问题标题】:Calculating duplicate permutations in Python在 Python 中计算重复排列
【发布时间】:2026-01-17 09:05:02
【问题描述】:

假设我有这个清单: [1,1,2,2] 我想遍历这个的所有排列。 如果我打印相同的排列将打印 4 次。 对于 [1,1,1,3],相同的将打印 6 次, 对于 [1,1,1,3,3] 12.

一般来说:(a1)!(a2)!...(an)! 在 Python 中是否有任何函数可以做到这一点? 如果没有,你能给我一个在 Python 中做的算法吗?

【问题讨论】:

  • 您在问题中包含了算法。您的公式定义了一种算法。
  • 好吧,我知道数学,但我真的不知道如何将这些知识暗示给 python
  • 你试过用谷歌搜索python中的阶乘吗?然后在python中乘以结果?我认为它不需要*编码器级别的 python 经验。
  • 基本的“python 排列”搜索会将您带到此处,您可以从中识别重复项:*.com/questions/104420/…
  • 嗯,我需要知道列表中每个项目的重复数量,而不是两次计算同一件事..

标签: python permutation


【解决方案1】:

您是否正在寻找类似以下的内容?

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

【讨论】: