python - 在Python中查找偶数斐波那契数之和的代码的内存错误

标签 python python-2.7

我正在编写代码,用于查找斐波那契数列中偶数项的总和,其值不超过 400 万。该代码对于高达 40k 的值可以正常工作,但是在查找高达 400 万的值时出现内存错误,有人可以帮我解决吗问题

我的代码是:

def fib(x):
    l=[0,1]
    m=[]
    a=0
    c=0
    b=1
    while len(l) <=x:
             d=c+b
             c=b
             b=d
             l.append(d)
             if d%2==0: 
                    m.append(d)
                    a=a+d
    print 
    print a 
    print m

最佳答案

按照我的理解澄清一下:您正在寻找一个函数,它返回斐波那契数列中所有偶数之和,最多 400 万。尝试使用两个单独的函数,如下所示。

斐波那契数列中给定数字的第一个函数:

    def fib(n):
        a = 0
        b = 1
        for e in range(n):
            old_a = a
            a = b
            b = old_a + b
        return a

第二个函数用于求和,它调用前面的函数(并使用计数,而不是列表,以便节省内存。):

    def even_sum(t):
        total = 0
        for x in range(t):
            fib_x = fib(x)
            if fib_x % 2 == 0:
                total += fib_x
                print fib_x     # <-- this line is optional,
                                # include it if you want to see each
                                # even number printed.
        return total

然后调用您的函数。例如:

打印even_sum(100)

这给了我们这个答案:

286573922006908542050

关于python - 在Python中查找偶数斐波那契数之和的代码的内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34150974/

相关文章:

python - 操作系统错误 : socket no longer exists (Python IDLE error)

python - 从 python-2.5 升级到 2.7 时带有 HTTPS 回归的 urllib2.ProxyHandler

python - PyLDAvis 可视化与生成的主题不一致

python - 在 UDF 之后将新列附加到现有 PySpark 数据帧

python - 并不总是包含在标签 Python Beautifulsoup 中的网页抓取属性

python - 如何解决此错误 : AttributeError: 'NoneType' object has no attribute 'write_audiofile'

python - 执行绝对路径包含空格的powershell文件

python - 函数 detectMultiScale 中的错误 : (-215) ! empty()

python - 如何知道什么是正确的编码?

python - 从 unicode 字符串中获取十六进制的 UTF-8 字符序列