在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
但是返回错误的结果(即单个元组)。谁能解释为什么,以及如何修复第二功能?