【发布时间】:2020-05-25 11:27:38
【问题描述】:
在 python 3 中,我正在尝试编写一个需要两个自然数的函数 ????和 ????作为输入并返回所有大小为 ???? 的元组的集合总和是????。
我已经构建了以下函数:
def get_tuples(length, total):
if length == 1:
yield (total,)
return
for i in range(total + 1):
for t in get_tuples(length - 1, total - i):
yield (i,) + t
其中,例如,list(get_tuples(2, 8)) 返回正确的结果,并且:
def get_tuples(length, total):
if length == 1:
return [(total,)]
comp = []
for i in range(total + 1):
for t in get_tuples(length - 1, total - i):
comp.append((i,) + t)
return comp
但是返回错误的结果(即单个元组)。 谁能解释一下为什么,以及如何修复第二个功能?
【问题讨论】:
-
元组包含正整数对吗?
-
你有一个
return在循环中,所以它在第一次通过时退出。 -
@Tupteq 谢谢,如果没有生成器,我怎样才能使第二个函数工作?
标签: python combinatorics