I am using recursive to find a happy number.
The following is my Python code:
deepth = 0
def is_happy_number(number):
astring = str(number)
global deepth
digits = [int(char) for char in astring]
sum_digit = sum([digit**2 for digit in digits])
if sum_digit == 1:
deepth = 0
return True
else:
deepth += 1
if deepth >800:
return False
return is_happy_number(sum_digit)
print '7',is_happy_number(7)
for number in range(1,11):
print number,is_happy_number(number)
The results are :
7 True
1 True
2 False
3 False
4 False
5 False
6 False
7 False
8 False
9 False
10 True
When I test number 7 alone, it returns 'True'. While I run the last two raws code, number 7 return 'False' .
I don't know which part is wrong.
After a few minutes, I find the wrong part in my Python code. And I add:
deepth = 0
after:
if deepth > 800:
With the remind of @Will, I find another solution to this problem. Code modified is as following:
def is_happy_number(number, deepth=0):
astring = str(number)
digits = [int(char) for char in astring]
sum_digit = sum([digit**2 for digit in digits])
if sum_digit == 1:
return True
else:
deepth += 1
if deepth >800:
return False
return is_happy_number(sum_digit,deepth)
print '7',is_happy_number(7,0)
for number in range(1,10):
if is_happy_number(number,0):
print number,
You're failing to reset the global variable depth
. A better way to deal with this is to pass the depth into the recursive call.
Something like this:
def is_happy_number(number, depth=0):
# ... as before ...
return is_happy_number(sum_digit, depth)
As Barak Manos has pointed out in his answer, the deepth
variable is the culprit here. It is not reset in the case where a depth of 800 is reached. If that is done, your code works:
deepth = 0
def is_happy_number(number):
astring = str(number)
global deepth
digits = [int(char) for char in astring]
sum_digit = sum([digit**2 for digit in digits])
if sum_digit == 1:
deepth = 0
return True
else:
deepth += 1
if deepth >800:
deepth = 0
return False
return is_happy_number(sum_digit)
print '7',is_happy_number(7)
for number in range(1,11):
print number,is_happy_number(number)
I totally agree with Will that you shouldn't use a global variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With