[英]Recursive functions in python
I just started learning python after scheme. 我刚开始学习计划之后的python。 Is recursion like
sum+=alist[0]+sumup(alist[1:])
not allowed? 是否不允许像
sum+=alist[0]+sumup(alist[1:])
递归? I get the error 我得到错误
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
The code: 编码:
m=int(input())
c=list(map(int,input().split()))
x,y=map(int,input().split())
sum=0
def sumup(alist):
global sum
if alist==[]:
return 0
else:
if sum<x:
sum+=alist[0]+sumup(alist[1:])
elif sum>=x:
return sum
elif sum>y:
return 0
sumup(c)
You forgot a return statement in the if sum <x:
clause: 您在
if sum <x:
子句中忘记了返回语句:
if sum<x:
sum+=alist[0]+sumup(alist[1:])
should be 应该
if sum<x:
sum+=alist[0]+sumup(alist[1:])
return sum
and also, another case - if sum <= y
you are not returning anything. 还有另一种情况-如果
sum <= y
,则不返回任何内容。 (You might want to get rid of elif sum>y
clause, as that would never happen. ) (您可能希望摆脱
elif sum>y
子句,因为那永远不会发生。)
Your recursive function returns None
for the case where alist
is not empty and sum < x
is True
. 对于
alist
不为空且sum < x
为True
的情况,您的递归函数将返回None
。
You'll need to get rid of the global sum
here however, as you are going to end up adding to that value whatever you return from recursive calls. 但是,您将需要在这里摆脱
global sum
,因为您最终将通过递归调用返回的值加到该值上。 That'll only lead to doubling the value. 那只会导致价值翻倍。
At most, make sum
a parameter to the function to pass along the value to recursive calls. 最多将
sum
作为函数的参数,以将值传递给递归调用。 You didn't provide us with sample input and output, so it is very hard to determine what you are trying to achieve with the function. 你没有为我们提供样品的输入和输出,所以很难确定你正在努力实现与功能是什么。
Last, but not least, the elif sum > y:
branch will never be executed, as one of sum < x
and sum >= x
will always be True
. 最后但并非最不重要的一点是,永远不会执行
elif sum > y:
分支,因为sum < x
和sum >= x
始终为True
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.