递归函数在Python中的斐波那契数列实现:

huangapple go评论94阅读模式
英文:

Recursive function in python for Fibonacci sequence

问题

我正在尝试使用递归函数来计算斐波那契数列。这是我想出来的代码:

import sys
new_recursion_limit=3000
sys.setrecursionlimit(new_recursion_limit)
fibonacci_cache = {}

def fibonacci(n):
    if n in fibonacci_cache:
        return fibonacci_cache[n]
    if n == 1:
        return 1
    else:
        result = fibonacci(n - 1) + fibonacci(n - 2)
        fibonacci_cache[n] = result
        return result

number = int(input("输入要计算斐波那契值的数字: "))
result = fibonacci(number)
print(f"斐波那契数列第{number}项的值是{result}")

我使用了ChatGPT以便能够基本了解如何实现这个方法。我收到的错误是RecursionError: maximum recursion depth exceeded。即使对于整数5,我也收到此错误。我是编程的初学者,正在尝试实现递归函数以更好地理解其运作方式。请问有人可以帮助我解决这个错误吗?

当我收到这个错误时,我尝试使用sys函数来设置递归限制。在这种情况下,重复次数超过1000。我原本期望递归函数能正常工作,但我仍然收到这个错误。

英文:

I am trying to use a recursive function to calculate the fibonacci sequence. This is what I have come up with:

import sys
new_recursion_limit=3000
sys.setrecursionlimit(new_recursion_limit)
fibonacci_cache = {}


def fibonacci(n):
    if n in fibonacci_cache:
        return fibonacci_cache[n]
    if n == 1:
        return 1
    else:
        result = fibonacci(n - 1) + fibonacci(n - 2)
        fibonacci_cache[n] = result
        return result



number = int(input("Enter the number for fiboonacci value: "))
result = fibonacci(number)
print(f"The value of fibbonaci {number} is {result}")

I used chatGPT so that I can have a basic idea to implement the method. The error I receive is a RecursionError: maximum recursion depth exceeded. even for the int 5 I am receiving this error. I am a beginner in programming and I am trying to implement the recursive function so that I have a proper idea about the functioning. Can anyone please help me with this error?

When I received the error I tried to use sys function to se a recursive limit. Th repetation is 1000+ in this case. I was expecting the recursive function to work normally. but I still receive the error.

答案1

得分: 2

核心问题是你需要考虑两个特殊情况,n == 1n == 0。你可以在你的代码中处理这些情况,但由于你手动初始化了缓存,也可以在那里处理。

## ----------------
## 以一种能处理特殊情况的方式初始化缓存。注意,这也简化了我们的方法。
## ----------------
fibonacci_cache = {0: 0, 1: 1}
## ----------------

def fibonacci(n):
    if n not in fibonacci_cache:
        fibonacci_cache[n] = fibonacci(n-1) + fibonacci(n-2)
    return fibonacci_cache[n]

number = int(input("输入要计算斐波那契数列值的数字:"))
result = fibonacci(number)
print(f"斐波那契数列第{number}项的值是{result}")

此时,你可以添加一个测试以确保 n >= 0,如果不是,则抛出 ValueError 异常,但我将让你自行考虑是否要添加。

英文:

As has been pointed out, the core issue here is that you need to account for two special cases, n == 1 and n == 0. You can do that in your code, but since you are manually initializing a cache you can also just do it there.

## ----------------
## initialize our cache in a way that will
## handle our special cases. Note that this
## also simplifies our method.
## ----------------
fibonacci_cache = {0: 0, 1: 1}
## ----------------

def fibonacci(n):
    if n not in fibonacci_cache:
        fibonacci_cache[n] = fibonacci(n-1) + fibonacci(n-2)
    return fibonacci_cache[n]

number = int(input("Enter the number for fiboonacci value: "))
result = fibonacci(number)
print(f"The value of fibbonaci {number} is {result}")

At this point, you might add in a test to ensure that n >= 0 and throw a ValueError if not, but I'll leave that to you to consider.

答案2

得分: 1

问题出现在您的代码到达fibonacci(2)的递归调用时。

在这个调用内部,它将调用fibonacci(1)fibonacci(0)

fibonacci(1)的调用中,它将触发if n == 1条件,并正确地终止,返回值为1。

fibonacci(0)的调用不会停止;它调用fibonacci(-1)fibonacci(-2)。而负数将继续增长。

您需要考虑n为零的情况。

英文:

The problem comes when your code gets to the recursive call of fibonacci(2).

Inside this call, it will then call fibonacci(1) and fibonacci(0).

In the fibonacci(1) call, it will hit the if n == 1 condition, and properly terminate with a return value of 1.

But the fibonacci(0) call does not stop; it calls fibonacci(-1) and fibonacci(-2). And the negative numbers just keep growing from there.

You need to account for the case where n is zero.

答案3

得分: 0

假设 n=2,在你的函数中,将会进入 else 分支,然后面临着 fibonacci(n - 1) + fibonacci(n - 2),即 fibonacci(1) + fibonacci(0)

fibonacci(1) 等于 1,但你没有提供 fibonacci(0) 的返回值,所以再次进入 else 分支,你将得到 fibonacci(-1) + fibonacci(-2),这将会无限循环下去。

因此,简单地为 n=0 的情况提供一个返回值:

def fibonacci(n):
    if n in fibonacci_cache:
        return fibonacci_cache[n]
    if n == 0:
        return 0
    if n == 1:
        return 1
    ...
英文:

Assume n=2, your else in your function would be met, then it faces fibonacci(n - 1) + fibonacci(n - 2), which is fibonacci(1) + fibonacci(0).

fibonacci(1) is 1, but you didn't provide anything for fibonacci(0), so again your else would be met and you will have fibonacci(-1) + fibonacci(-2) and this will happen infinitely.

So simply just provide a return value for case of n=0:

def fibonacci(n):
    if n in fibonacci_cache:
        return fibonacci_cache[n]
    if n == 0:
        return 0
    if n == 1:
        return 1
    ...

答案4

得分: -1

观察当函数接收到 n=2 时的操作。

英文:

Look at what your function does when it receives n=2

huangapple
  • 本文由 发表于 2023年8月4日 22:03:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定