Recursion function not working properly

后端 未结 4 609
一向
一向 2020-12-07 06:08

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)         


        
4条回答
  •  长情又很酷
    2020-12-07 06:20

    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.

    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.

提交回复
热议问题