gpt4 book ai didi

Python 大量崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 10:50:04 24 4
gpt4 key购买 nike

我是 Python 的新手,但我遇到了递归创建斐波那契生成器的挑战,让我开始学习这门语言。问题是,如果我发现超过 3226/3227 个斐波那契数,Python 就会崩溃。 ( python 3)

注意:我用 PHP、JavaScript 做过很多编程,用过一点 VBA,用过一点 Java,但我对 Python 完全陌生。因此,如果这只是错误的数据类型或其他问题,我真的很抱歉。

import sys
sys.setrecursionlimit(1000000000)

cache = dict()

def fibonacci(n, arr = False):
global cache

if n == 0 or n == 1:
r = n
else:
nVal1 = n - 1
nVal2 = n - 2
if (not nVal1 in cache):
num1 = cache[nVal1] = fibonacci(nVal1, arr)
else:
num1 = cache[nVal1]
if (not nVal2 in cache):
num2 = cache[nVal2] = fibonacci(nVal2)
else:
num2 = cache[nVal2]

r = num1 + num2


if arr != False:
arr.append(r)


return r

fib = list()
# 3227 is max without generating a list.
# 3226 is max when generating a list.
fibonacci(3226, fib)
for x in fib: print(x)

我该怎么做才能让它走得更远?我不认为它已经耗尽内存,因为它在我的慢速 i3 笔记本电脑上运行了大约两秒钟......

最佳答案

阅读来自 sys.setrecursionlimit 的笔记

The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.

我会这样实现 fibo

def fib():
a,b = 1,0
while True:
yield a
b = a+b
yield b
a = a+b

fibs = fib()
fibo = [next(fibs) for i in xrange(100)]

关于Python 大量崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14542739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com