[英]Sum of integers with tuples inside a tuple
I'm trying to return the sum of all elements on a set of tuples inside tuples, but the last value is always None
, so I get我试图返回元组内的一组元组上所有元素的总和,但最后一个值总是
None
,所以我得到
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
using the code below.使用下面的代码。
How do I skip this last value?如何跳过最后一个值?
It has to be done with recursion.它必须通过递归来完成。
L = (1, (2, (3, None)))
def sum(L):
if not L:
return None
else:
return L[0] + sum(L[1])
If that is really the structure of your tuple, just return zero when you reach the end:如果这确实是您的元组的结构,则在到达末尾时返回零:
def my_sum(L):
if not L:
return 0
else:
return L[0] + my_sum(L[1])
And don't shadow the name of a built-in.并且不要隐藏内置的名称。 It's bad practice, even if it's technically legal.
这是不好的做法,即使它在技术上是合法的。
Also, I don't think this is necessarily a good candidate for recursion.另外,我认为这不一定是递归的好选择。 An iterative solution works the same, and without creating a new stack frame for every level:
迭代解决方案的工作原理相同,并且无需为每个级别创建新的堆栈框架:
s = 0
while L:
s += L[0]
L = L[1]
That's just a personal bonus for when you can make the design decision.这只是您做出设计决定时的个人奖励。
In [117]: L = (1, (2, (3, None)))
...:
...: def sum(L):
...: if not L:
...: return 0
...: else:
...: return L[0] + sum(L[1])
...:
In [118]: sum(L)
Out[118]: 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.