【发布时间】:2022-11-14 05:02:59
【问题描述】:
我当前的程序打印使用给定整数生成的所有不同总和。而不是程序打印列表的内容,我只想打印列表的长度。
def sums(items):
if len(items) == 1:
return items
else:
new_list = []
for i in items:
new_list.append(i)
for x in sums(items[1:]):
new_list.append(x)
new_list.append(x + items[0])
new_list = list(set(new_list))
return new_list
if __name__ == "__main__":
print(sums([1, 2, 3])) # should print 6
print(sums([2, 2, 3])) # should print 5
只是编辑求和函数,而不是 return new_list 我尝试 return len(new_list) 这给了我 TypeError: 'int' object is not iterable 的错误。我只是想返回列表的长度,所以我不太明白这个错误。
【问题讨论】:
-
你的代码对我来说运行没有错误,但是如果你返回长度,因为你有一个整数,这将破坏需要一个列表作为输入的递归函数。你能解释一下你想要达到的目标吗?
-
如果您想要唯一值的总和,则不需要递归函数:
sum(set(items))