views:

167

answers:

4

Can somebody tell me why this should be wrong?

#Each new term in the Fibonacci sequence is generated
#by adding the previous two terms. By starting with 1 and 2,
#the first 10 terms will be:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#Find the sum of all the even-valued terms in the sequence
#which do not exceed four million.


sum=2

list = [1,2]
for x in range(2,100):
    a = list[x-2]+list[x-1]
    print(a)
    list.append(a)
    if a % 2 == 0:
        sum += a
        print('sum', sum)
        if sum >= 4000000:
            break
+4  A: 

replace

    sum += a
    print('sum', sum)
    if sum >= 4000000:
        break

with

    if a > 4000000:
        break
    sum += a
    print('sum', sum)

You should compare "a" with 4000000, not "sum", like Daniel Roseman said.

Christopher Bruns
+2  A: 

The question asked for the sum of even terms which do not exceed four million. You're checking if the sum doesn't exceed 4m.

Daniel Roseman
+4  A: 

Here's a completely different way to solve the problem using a generator and itertools:

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

import itertools
print sum(n for n in itertools.takewhile(
    lambda x: x <= 4000000, fib()) if n % 2 == 0)

Output:

4613732

So your code, even though it is wrong (see other answers), happens to give the correct answer.

Mark Byers
A: 

I'm trying to solve the same problem - although I understand the logic to do it, I don't understand why this works (outputs the right sum)

limit = 4000000
s = 0

l = [1,2]
while l[-1]<limit:
    n = l[-1]+l[-2]
    l.append(n)
    print n

And then then moment I put in the modulo function, it doesn't output anything at all anymore.

limit = 4000000
s = 0

l = [1,2]
while l[-1]<limit:
    n = l[-1]+l[-2]
    if n % 2 == 0 :
        l.append(n)
        print n

I'm sure this is fairly simple...thanks!

Laurier