简体   繁体   中英

a recursive function to calculate sum of a number digits

i have to write a recursive function which calculates sum of a number digits,here's the code i tried :

def sum_digit(n):
   sum=0
   a = n % 10
   n //= 10
   sum += a
   while n > 0 :
      sum = sum + sum_digit(n)
   return sum


print(sum_digit(67154))

i don't know why i don't get the 23 as answer...my program doesn't come to an end

for example 23 number(please correct me if I'm wrong,I'm a newbie in python),the 3 goes to sum, and n become2,since its > 0 then it should go to while,so now it should calculate sum digit(2),the a become 2 and 2 goes to sum and n become 0 and sum digit(2) returns 2,then it sum with the 3 and i must get 5. i appreciate your help.

You have an infinite loop because n never changes within the loop. Note that assigning a new value to n in the scope of the called function will not change n in the outer scope.

Also, it seems you are mixing an iterative solution with a recursive one. If you do the recursive call, you do not need the loop, and vice versa.

You can either do it recursively:

def sum_digit(n):
    if n > 0:
        return sum_digit(n // 10) + n % 10
    else:
        return 0

Or in an iterative way:

def sum_digit(n):
    s = 0
    while n > 0:
        s += n % 10
        n //= 10
    return s

Or just using bultin functions (probably not what your teacher wants to see):

def sum_digit(n):
    return sum(map(int, str(n)))

我必须用if来更改时间,并且它的工作原理非常感谢您的评论,并很抱歉在此处发布这样的问题。

This will do the trick:

def sum_digit(n, current_sum=0):
    if n == 0:
        return current_sum
    else:
        digit = n % 10
        current_sum += digit
        n //= 10
        return sum_digit(n, current_sum)

The output:

print(sum_digit(67154))
> 23

You were mixing up an iterative method (the while loop) and the recursive method (the function call).

In a recursive function, must make sure you get these things right:

The end condition (in our case, we return the sum when the digit is 0)

and

The recursive call (in our case, going down one digit each time)

Change your code as following:

def sum_digit(n):
   sum=0
   a = n % 10
   n //= 10
   sum += a
   if n > 0 :
      sum = sum + sum_digit(n)
   return sum

The reason is n is assigned new reference inside function, but it's invisible outside. so while part is loop died. In fact, while part is executed at most once, so code was changed as above.

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