获取所有加起来为数字的数字 [英] Get all numbers that add up to a number
本文介绍了获取所有加起来为数字的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到一种方法来显示所有可能的X整数集,这些X整数加起来等于一个给定的整数.例如,要获得所有2个整数集,使我得到5个:
I'm trying to find a way to display all the possible sets of X integers that add up to a given integer. for example to get all 2 integer sets that make 5 I would have:
1, 4
2, 3
或为3个整数组成6:
1, 1, 4
1, 2, 3
2, 2, 2
我只需要不包括0的整数,并且最多只需要处理一组中的15个和最大30个.数字.
I only need whole numbers not including 0 and it only needs to work on up to about 15 in a set and 30 max. number.
我什至不确定数学上是否有这个术语.我猜这类似于分解因子吗?
I'm not even sure if this has a term mathematically. It's similar to factorisation I guess?
推荐答案
这是解决此问题的一种方法:
Here is one way to solve this problem:
def sum_to_n(n, size, limit=None):
"""Produce all lists of `size` positive integers in decreasing order
that add up to `n`."""
if size == 1:
yield [n]
return
if limit is None:
limit = n
start = (n + size - 1) // size
stop = min(limit, n - size + 1) + 1
for i in range(start, stop):
for tail in sum_to_n(n - i, size - 1, i):
yield [i] + tail
您可以像这样使用它.
for partition in sum_to_n(6, 3):
print partition
[2, 2, 2]
[3, 2, 1]
[4, 1, 1]
这篇关于获取所有加起来为数字的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文