Recursion function not working properly
Posted
by jakecar
on Stack Overflow
See other posts from Stack Overflow
or by jakecar
Published on 2010-06-01T00:24:47Z
Indexed on
2010/06/01
0:33 UTC
Read the original article
Hit count: 202
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.
© Stack Overflow or respective owner