def sum_digits(n):
if n < 10:
return n
else:
return int(str(n)[len(str(n))-1]) + sum_digits(n - int(str(n)[len(str(n))-1]))
#TEST
print(sum_digits(22541))
Asked
Active
Viewed 54 times
0

Rishit Dagli
- 1,000
- 8
- 20

김광윤
- 1
-
1What are you trying to do with your code? – xavc Jul 11 '20 at 04:38
-
To limit the recursions, you can do `sys.setrecursionlimit(limit)`. – Péter Leéh Jul 11 '20 at 04:41
-
Does this answer your question? [Sum the digits of a number - python](https://stackoverflow.com/questions/14939953/sum-the-digits-of-a-number-python) – sushanth Jul 11 '20 at 04:45
-
3@xavc I guess this is a try to get into the famous Stack Overflow series "Things you should not do with recursion done recursively". – Klaus D. Jul 11 '20 at 04:46
1 Answers
0
A better way to calculate the sum of the digits of a number using recursion is
def sumOfDigits(n) :
if n == 0 :
return 0
else :
return n%10 + sumOfDigits(n//10)

Samudra Ganguly
- 637
- 4
- 24