递归函数无法正常工作
我很难弄清楚这里出了什么问题:
class iterate():
def __init__(self):
self.length=1
def iterated(self, n):
if n==1:
return self.length
elif n%2==0:
self.length+=1
self.iterated(n/2)
elif n!=1:
self.length+=1
self.iterated(3*n+1)
例如,
x=iterate()
x.iterated(5)
输出 None
。它应该输出 6,因为长度如下所示: 5 --> 16 --> 8 --> 4 --> 2 --> 1
经过一些调试,我发现 self.length
正确返回,但递归中出现问题。我不太确定。感谢您的任何帮助。
I'm having quite a hard time figuring out what's going wrong here:
class iterate():
def __init__(self):
self.length=1
def iterated(self, n):
if n==1:
return self.length
elif n%2==0:
self.length+=1
self.iterated(n/2)
elif n!=1:
self.length+=1
self.iterated(3*n+1)
For example,
x=iterate()
x.iterated(5)
outputs None
. It should output 6 because the length would look like this:
5 --> 16 --> 8 --> 4 --> 2 --> 1
After doing some debugging, I see that the self.length
is returned properly but something goes wrong in the recursion. I'm not really sure. Thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在两个
elif
块中,进行递归调用后不会返回值。在递归调用iterated
之前,您需要一个return
(例如return self.iterated(n/2)
)。如果您没有显式return
,该函数将返回None
。这将解决这个问题,但有一种方法可以使您的代码更简单:您实际上不需要成员
length
。相反,您可以将递归调用的结果加 1:这不需要位于类中,因为不需要任何成员。
In the two
elif
blocks, you don't return a value after making the recursive call. You need areturn
before the recursive calls toiterated
(e.g.return self.iterated(n/2)
). If you don't explicitlyreturn
, the function will returnNone
.That will fix this issue, but there is a way to make your code simpler: You don't actually need the member
length
. Instead, you can add 1 to the result of the recursive call:This doesn't need to be in a class, since there is no need for any members.
您缺少返回语句:
You're missing the return statements:
您仅从最深层次的递归返回一个值,然后在第二深层次上忽略它。
所有
self.iterated(...)
行都应为return self.iterated(...)
You are only returning a value from the deepest level of recursion, then ignoring it on the second-deepest level.
All of the
self.iterated(...)
lines should readreturn self.iterated(...)
您应该使用
return self.iterated(...)
而不仅仅是self.iterated(...)
来完成每个 elif 分支You should finish each elif branch with
return self.iterated(...)
rather than justself.iterated(...)