Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,
like image 439
zero Avatar asked Apr 29 '15 12:04

zero


2 Answers

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)
like image 50
Will Avatar answered Sep 28 '22 04:09

Will


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.

like image 35
wonderb0lt Avatar answered Sep 28 '22 06:09

wonderb0lt