递归函数不能正常工作 [英] Recursion function not working properly

查看:67
本文介绍了递归函数不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚这里出了什么问题:

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)

例如,

x=iterate()
x.iterated(5)

输出 None.它应该输出 6 因为长度看起来像这样:5 --> 16 --> 8 --> 4 --> 2 --> 1

outputs None. It should output 6 because the length would look like this: 5 --> 16 --> 8 --> 4 --> 2 --> 1

在进行一些调试后,我看到 self.length 正确返回,但递归中出现问题.我不太确定.感谢您的帮助.

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.

推荐答案

在两个 elif 块中,您在进行递归调用后不返回值.在递归调用 iterated(例如 return self.iterated(n/2))之前,您需要一个 return.如果你没有明确return,函数将返回None.

In the two elif blocks, you don't return a value after making the recursive call. You need a return before the recursive calls to iterated (e.g. return self.iterated(n/2)). If you don't explicitly return, the function will return None.

这将解决这个问题,但有一种方法可以使您的代码更简单:您实际上并不需要成员 length.相反,您可以将递归调用的结果加 1:

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:

def iterated(n):
    if n==1:
        return 1
    elif n%2==0:
        return 1 + iterated(n/2)
    else:
        return 1 + iterated(3*n+1)

print(iterated(5))

这不需要在一个类中,因为不需要任何成员.

This doesn't need to be in a class, since there is no need for any members.

这篇关于递归函数不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆