What is wrong with my Python code containing a recursive function?

I use recursive lucky number search.

The following is the 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) 

Results:

 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 only number 7, it returns True. As I run the last two raws codes, number 7 returns "False".

I don’t know which part is wrong.

After a few minutes, I find the wrong part of the Python code. And I add:

 deepth = 0 

after

 if deepth > 800: 

With a reminder of @Will, I find another solution to this problem. The modified code is as follows:

 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, 
+5
source share
3 answers

You do not reset the global variable depth . The best way to handle this is to pass the depth into a recursive call.

Something like that:

 def is_happy_number(number, depth=0): # ... as before ... return is_happy_number(sum_digit, depth) 
+8
source

As Barak Manos pointed out in his answer, here the deepth variable is the offender. This will not reset if you reach a depth of 800. If this is done, your code will work:

 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 should not use a global variable.

+6
source

The problem arises because you define deepth only once. Then the previous value is reused. To solve this problem, you should set deepth to 0 when returning False or True.

0
source

All Articles