recursion - What's wrong with my Python code containing recursive function? -


i using recursive find happy number.

the following python code:

deepth = 0 def is_happy_number(number):     astring = str(number)     global deepth     digits = [int(char) char in astring]     sum_digit = sum([digit**2 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) number in range(1,11):     print number,is_happy_number(number) 

the results :

7 true 1 true 2 false 3 false 4 false 5 false 6 false 7 false 8 false 9 false 10 true 

when test number 7 alone, returns 'true'. while run last 2 raws code, number 7 return 'false' .

i don't know part wrong.

after few minutes, find wrong part in python code. , add:

deepth = 0 

after:

if deepth > 800: 

with remind of @will, find solution problem. code modified following:

def is_happy_number(number, deepth=0):     astring = str(number)     digits = [int(char) char in astring]     sum_digit = sum([digit**2 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) number in range(1,10):     if is_happy_number(number,0):         print number, 

you're failing reset global variable depth. better way deal pass depth recursive call.

something this:

def is_happy_number(number, depth=0):     # ... before ...     return is_happy_number(sum_digit, depth) 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -