[Solved] Python 3 Recursion – Maximum Depth Exceeded


From the question, it seems that you want to compute

\sum_{i=1}^{n} 1/i

If the input is 0, then returns 0.

Remember that in a recursive function, you need to define a base case and an inductive clause.

In your question, the inductive clause is:

1.0 / i + sum_of_reciprocals(i-1)

while the base case can be set to 0 when i=0.

Given this formulation, the function with an example looks like:

def sum_to(n):
    if n > 0:
        return sum_to(n-1) + 1.0 / n
    else:
        return 0

if __name__ == '__main__':
    print(sum_to(3))

and the result is 1.83333333333.

For more information about recursive functions, you can start from the related wikipedia page.

1

solved Python 3 Recursion – Maximum Depth Exceeded