如何生成给定长度和元素总和的所有元组的集合? [英] How to generate a set of all tuples of given length and sum of elements?
本文介绍了如何生成给定长度和元素总和的所有元组的集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想拥有一个函数,该函数生成具有给定长度和元素总和的所有可能元组的集合(或列表)。元组的元素不能为负整数。
I would like to have a function that generates a set (or a list) of all possible tuples with a given length and sum of their elements. The elements of tuples should be not negative integer.
例如,以下输入
get_tuple(length=3, total=2)
我想获得以下输出:
[(1, 0, 1), (2, 0, 0), (1, 1, 0), (0, 0, 2), (0, 1, 1), (0, 2, 0)]
是标准库在Python中可以做到这一点?如果没有,如何编写一个可以做到的函数?
Is the a standard library in Python that can do that? If not, how to write a function that can do it?
推荐答案
您可以创建一个递归函数,避免创建所有候选组合并检查它们的总和:
You can create a recursive function, avoiding creating all candidate combinations and checking their sums:
def get_tuples(length, total):
if length == 1:
yield (total,)
return
for i in xrange(total + 1):
for t in get_tuples(length - 1, total - i):
yield (i,) + t
如果我们测试:
>>> list(get_tuples(3, 2))
[(0, 0, 2), (0, 1, 1), (0, 2, 0), (1, 0, 1), (1, 1, 0), (2, 0, 0)]
这篇关于如何生成给定长度和元素总和的所有元组的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文