下面的 2 个示例中哪一个是使用递归显示斐波那契数列的更有效方法?
第一个示例是使用列表来存储数字。第二个是使用 for 循环。 我很难理解为什么有人会使用 for 循环,因为它可以在递归函数本身内部完成。
示例 1:
def fib(a, n):
a.append(n)
if len(a) == 9:
return n
else:
return fib(a, n + a[-2])
a = [0]
n = 1
result = fib(a, n)
print(f"9th number = {result}")
示例 2:
def fib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))
n = 9
for i in range(n):
print(fib(i))
The first example is using a list to store the numbers. The second one is using a for loop.
I have trouble understanding why would anyone use a for loop when it can be done inside the recursion function itself.
Example 1:
def fib(a, n):
a.append(n)
if len(a) == 9:
return n
else:
return fib(a, n + a[-2])
a = [0]
n = 1
result = fib(a, n)
print(f"9th number = {result}")
Example 2:
def fib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))
n = 9
for i in range(n):
print(fib(i))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

一般来说,不,在任何具有两种形式的可行实现的实际用法中,递归不会比循环更快。我的意思是,当然,你可以编写永远需要的循环,但是会有更好的方法来实现相同的循环,它可以优于通过递归实现相同问题的任何实现......
所以我认为递归更好
In general, no, recursion will not be faster than a loop in any realistic usage that has viable implementations in both forms. I mean, sure, you could code up loops that take forever, but there would be better ways to implement the same loop that could outperform any implementation of the same problem via recursion....
So i think recursion is better