这是解决此问题的一种方法:
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]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)