Rizz_Beginner_Python
Rizz_Beginner_Python

Reputation: 31

What's wrong in this simple python code?

Why is it not giving out correct total of first even fibonacci numbers upto 4 mn?

x = 1
y = 2
list = [1,2]
while y< 4000000:
    z= x+y
    x=y
    y=z
    list.append (y)
list_even = []
for a in list:
    if a%2 == 0:
        list_even.append (a)
else:
    pass

total = sum(list_even)
print (total) 

Upvotes: 2

Views: 133

Answers (3)

Copperfield
Copperfield

Reputation: 8510

just for fun, this is an one liner version

from itertools import takewhile

def fib():
    fk, fk1 = 0,1
    while True:
        yield fk
        fk, fk1 = fk1, fk+fk1

print( sum( x for x in takewhile(lambda f:f<4000000,fib()) if x%2==0 ) )

here takewhile will stop the iteration when the condition is no longer satisfied the same way as the others answers

Upvotes: 2

Tagc
Tagc

Reputation: 9076

There are other answers already addressing specific bugs in your code, so I want to offer a completely different implementation that achieves your stated goal:

giving out correct total of first even fibonacci numbers upto 4 mn

If you want to find the sum of the even Fibonacci numbers up to some limit, the code below might be a more functional way of achieving it. It's based on composing Python generators, which should help make the code easier to follow and more reusable.

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

def evens(l):
    for x in l:
        if x % 2 == 0:
            yield x

def sum_even_fibonacci(limit):
    total = 0

    for x in evens(fib()):
        if total + x > limit:
            return total

        total += x

if __name__ == '__main__':
    print(sum_even_fibonacci(4000000))

Output

1089154

Edit

It's ambiguous what exactly OP is asking.

  • If OP wants to sum the even Fibonacci terms until the sum would surpass 4,000,000, then the answer is what I stated above - 1089154.

  • If OP wants to sum all even Fibonacci terms under 4,000,000, then the expression if total + x > limit would change to x > limit and the answer would be 4613732.

Upvotes: 6

Aryaman
Aryaman

Reputation: 3426

I recognize this as Problem 2 on Project Euler. For some reason, @Tagc is getting the wrong answer. I used a generator as well but not a list. Here was my solution:

def fibonacci():
    term_0, term_1 = 1,2
    while True:
        yield term_0 + term_1
        term_0, term_1 = term_1, term_0 + term_1

fibonacci_sum = 2
for n in fibonacci():
    if n > 4000000: break
    if n % 2 == 0: fibonacci_sum += n

print(fibonacci_sum)

Output:

$ python 002.py
4613732

Upvotes: 2

Related Questions