I have written a function to print of sum of numbers to n.
def sumOfDigits(n):
sum = 0
if n < 0:
print("Enter a positive number")
else:
while (n > 0):
sum = sum + n
n -= 1
return sum
print(sumOfDigits(4))
Which prints the result fine but now i am trying to do it recursively.
def sumOfDigits(n):
assert n >= 0 and int(n) == n, 'The number must be positive integer only'
if n == 0:
return 0
else:
while n > 0:
return sumOfDigits(n) + sumOfDigits(n-1)
print(sumOfDigits(3))
But i am getting the following error :-
assert n>= 0 and int(n) == n, 'The number must be positive integer only'
RecursionError: maximum recursion depth exceeded in comparison
Any help will be appreciated. Thank you.
>Solution :
In recursion, all the recursive calls must get you closer to the base case. When you call sumOfDigits(n), it just repeats the same value, so it recurses infinitely.
You just need to add the current value to the recursive result, not two recursive calls. So the line
return sumOfDigits(n) + sumOfDigits(n-1)
should just be
return n + sumOfDigits(n-1)
You also don’t need a while loop. The recursion is the loop.
def sumOfDigits(n):
assert n >= 0 and int(n) == n, 'The number must be positive integer only'
if n == 0:
return 0
else:
return n + sumOfDigits(n-1)
Your while loop is infinite because it never changes n.