Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

python - Recursion function not working properly

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...