Python 3 Recursion - Maximum Depth Exceeded

时光怂恿深爱的人放手 提交于 2019-12-25 20:05:10

问题


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.


回答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:

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.




回答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 is 2, which is > 0
    call sum_to(1/2)
        n is .5, which is > 0
        call sum_to(1/.5)
            n is 2, which is > 0
            call 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:

def sum_to(n):
    return 1 + 1/n

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



来源:https://stackoverflow.com/questions/36163040/python-3-recursion-maximum-depth-exceeded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!