简体   繁体   English

Python分区功能

[英]Python partition function

I have the following code which I adapted from code that was previously posted on this site. 我具有以下代码,这些代码是我根据以前在此网站上发布的代码改编而成的。 It is a variation on the a partition function that outputs all possible combination of numbers that add up to a specified sum, but it limits the numbers that can be used for the sum to a limited input list. 它是分区函数的一种变体,它输出所有可能的数字组合,这些数字加起来等于指定的总和,但是它将可用于总和的数字限制为有限的输入列表。

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)

results: 结果:

24 Combination of [5, 6, 7, 8, 9, 10] in 32 are: 24 [5、6、7、8、9、10]在32中的组合是:

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

Process finished with exit code 0 流程结束,退出代码为0

Everything is working as expected but I want to change it so each number can only be used once or none at all in each possible combination. 一切都按预期工作,但是我想更改它,因此每个数字只能使用一次,或者在每种可能的组合中根本不能使用。

So for example: "[10, 8, 7, 7], [10, 7, 5, 5, 5]," These combination sums would not be outputted since they contain repeating sevens and fives respectively. 因此,例如:“ [10、8、7、7],[10、7、5、5、5]”,由于这些组合和分别包含重复的7和5,因此不会输出。

I'm trying to keep the generator functions because I was told that they have better performance than lists and I might use the same function for larger lists and sums in the future. 我之所以要保留生成器函数,是因为有人告诉我它们的性能要比列表更好,并且将来我可能会对更大的列表和总和使用相同的函数。 But I am not sure how to check the generator for duplicate numbers to eliminate the sub-lists that contain repeating numbers. 但是我不确定如何检查生成器中是否存在重复编号,以消除包含重复编号的子列表。

Thanks. 谢谢。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM