简体   繁体   中英

Calculate the sum of the digits of a number recursively in Python

I'm having troubles with a recursive function in Python. The objective is for the function to calculate the sum of the digits of a number recursively.

This is what I have so far -- I realise that this version isn't as succinct as it could be, but right now I'm just trying to understand why it isn't working as is:

total = 0          #global variable declaration

def digit_sum(n):
    global total   #to be able to update the same variable at every level of recursion
    total += n % 10   #adding the last digit to the total
    n //= 10    #removing the last digit of the number
    if n < 10:
        total += n
        return total
    else:
        digit_sum(n)

print 'The return value of the function is: ', digit_sum(12345)
print 'The final value stored in total is: ', total

I obtain the following output:

 The return value of the function is:  None
The final value stored in total is:  15

My function is somewhat working, since the final value stored in the global variable total is correct, but printing the function output returns None instead of 15.

Could you please help me understand why?

Thank you.

Interesting problem, and an interesting solution! Let me debug with a more simple number - 421 .

  1. On first call, total is assigned the value 1 and n becomes 42 . The else branch gets executed.
  2. On second call, total gets value of 3 and n becomes 4 . The if branch is executed and the value total = 7 is return ed.

So, why are we seeing the None ? Let's inspect the call-stack:

> digit_sum(n = 421)
> > digit_sum(n = 42) # call to digit_sum from inside digit_sum
> -< 7                # value returned by inner/second call
> None

As you can notice, the value being returned by the second call is received by the first call, but the first call doesn't return the value being returned by the second call, so that's why you are seeing None .

But why does't first call return the value being returned by the second call?

Because of this line:

else:
    digit_sum(n)

You are calling the function a second time, but you are not returning its return value.

Hope it helps! :)

The problem is that you didn't add a return statement in your else clause.

Adding 'return digit_sum(n)' should solve your problem:

if n < 10:
    total += n
    return total
else:
    return digit_sum(n)

Example

When you have a recursive function (I'll take n! as example), calls are made until you reach a 'base case' (2 in n! and for you if n<10).

Let's take a look at factorial:

def fact(n):
    if(n<=2):
        return n
    else:
        return n*fact(n-1)

Without the return statement in else clause, if you ask for fact(4), this will also return none.

  • Here are the 'calls' with the return statement:

    1. return (4*fact(3))

    2. return (4*(3*fact(2)))

    3. return (4*(3*(2)))

Which gives 24.

  • Here are those without:

    1. (4*fact(3))

    2. (4*(3*fact(2)))

    3. (4*(3*(2)))

So the calculus is made, but nothing is returned.

I hope this will help you to understand.

NB: Here is a factorial implementation where recursivity is explained.

my solution is

def f(n):
    if n/10 == 0:
         return n
    return n%10 + f(n/10)

output:

f(12345) = 15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM