Skip to content Skip to sidebar Skip to footer

Python 3 Recursion - Maximum Depth Exceeded

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.

Solution 1:

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:

defsum_to(n):
    if n > 0:
        return sum_to(n-1) + 1.0 / n
    else:
        return0if __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.

Solution 2:

Trace through it to see if you ever reach your end condition:

(PS: at the time I wrote this the question's code was return 1 + sum_to(1/n))

sum_to(2):
    n is2, which is > 0call sum_to(1/2)
        n is .5, which is > 0call sum_to(1/.5)
            n is2, which is > 0call sum_to(1/2)
...

Your function never returns. The result would be infinite if you had infinite time and space to finish the calculation, since there is no end to the algorithm.

For your example, just write it this way:

defsum_to(n):
    return1 + 1/n

What is the expected result when n > 2? That will determine how to approach organizing working code.

Post a Comment for "Python 3 Recursion - Maximum Depth Exceeded"