Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中查找偶数斐波那契数和的代码内存错误_Python_Python 2.7 - Fatal编程技术网

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

python中查找偶数斐波那契数和的代码内存错误,python,python-2.7,Python,Python 2.7,我正在编写代码,用于在Fibonacci序列中查找值不超过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

我正在编写代码,用于在Fibonacci序列中查找值不超过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
def fib(x):
l=[0,1]
m=[]
a=0
c=0
b=1
当len(l)尝试以下方法时:

def sum_fib(x):
    a = 0
    c = 0
    b = 1
    l = 2
    while l <=x:
             d = c + b
             c = b
             b = d
             l += 1
             # yoda conditions check
             if 0 == d % 2: # using binary should be faster (0 == d & 1)
                    a += d
    print 
    print a 
def sum_fib(x):
a=0
c=0
b=1
l=2

而注释中所说的l则用计数器代替l。如果您需要打印所有偶数fib数字,请保留m,否则将其一起删除

初始化计数

count = 2

在while循环中,每次递增计数1

如我在评论中所述,这是一个消除不必要列表的版本。请注意,仍然会有一个指数增长的总和,这是不可避免的:

def fib(x):
    lc=2
    mc=0
    a=0
    c=0
    b=1
    while lc <=x:
        d=c+b
        c=b
        b=d
        lc += 1
        if d%2==0:
            mc += 1
            a += d
    print
    print a
    print mc
def fib(x):
lc=2
mc=0
a=0
c=0
b=1

而lc只是为了澄清我的理解:您正在寻找一个函数,它返回斐波那契序列中所有偶数的总和,高达400万。用两个独立的函数来尝试它

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

    def fib(n):
        a = 0
        b = 1
        for e in range(n):
            old_a = a
            a = b
            b = old_a + b
        return a
第二个函数用于调用前面函数的sum(并使用计数,而不是列表,以节省内存):

def偶数和(t):
总数=0
对于范围(t)内的x:
fib_x=fib(x)
如果fib_x%2==0:
总+=纤维x

打印fib_#x#嗯,您正试图创建非常长的列表。为什么不干脆把
l
m
一起去掉,而只保留计数器多长时间?那么你几乎不会使用任何内存。在删除l和M后,如何使用计数器将
l
替换为
lc
l
的长度。将其初始化为2。将
len(l)
替换为
lc
。将
l.append(d)
替换为
l+=1
。您可以对
m
执行相同的操作,将其初始化为0。请参阅下面我发布的答案,它与我描述的完全相同。它不打印
m
,但打印长度。
    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