I'm writing a basic recursion function that takes an integer, n, and returns the sum of the first n reciprocals. Inputting 2 should result in 1.5, and inputting 0 should return 0.
sum_to(2) = (1 + 1/2) = 1.5
Here's what I have:
def sum_to(n):
if n>0:
return sum_to(1+1/n) # Not sure if this is correct
return 0
But all I'm getting is a Maximum recursion depth exceeded. I know I could lists to solve this, but recursion is really intriguing and I want to find a solution using it.
return sum_to(n-1) + 1 / n if n > 0 else 0return 0toprint 0; now when n reaches 0 your function will returnNoneand the addition will fail. You need to return a number from each condition. (so just undo that edit :) )