Python分区函数



我有以下代码,这些代码是根据以前发布在这个网站上的代码改编的。它是一个分区函数的变体,它输出所有可能的数字组合,这些数字加起来就是一个指定的和,但它将可用于求和的数字限制在一个有限的输入列表中。

def part(nr, Nums):
nrs = sorted(Nums, reverse=True)
def inner(n, i):
if n == 0:
yield []
for k in range(i, len(nrs)):
if nrs[k] <= n:
for rest in inner(n - nrs[k], k):
yield [nrs[k]] + rest
return list(inner(nr, 0))

#List of numbers to form the sums.
Nums = [5,6 ,7 ,8, 9, 10]
#the total that the numbers add up to.
total = 32
tr = part(total, Nums)
print(f"{len(tr)}  Combination of {Nums} in {total} are:")
print(tr)

结果:

24 32中[5,6,7,8,9,10]的组合为:

[[10,10,7,5],[10,10,6,6],[10、9、8、5]、[10,9、7、6]、[10、8、6]、[10、8、7、7]、[10。5],[9,6,6,5],[8,8,8,8],[8、8、6、5,5],[7、7、7、5、5]、[8、7,6、6、6,6],[7,7,6,5,[6,6,5,5,5]]

进程结束,退出代码为0

一切都按预期进行,但我想更改它,使每个数字在每个可能的组合中只能使用一次或根本不使用。

例如:"[10,8,7,7],[10,7,5,5,5],"这些组合和将不会输出,因为它们分别包含重复的7和5。

我试图保留生成器函数,因为我被告知它们比列表有更好的性能,将来我可能会对更大的列表和总和使用相同的函数。但我不知道如何检查生成器中是否有重复的数字,以消除包含重复数字的子列表。

谢谢。

您可以将第7行更改为:for k in range(i + 1, len(nrs)):

最新更新