Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python _ Project Euler Question 2 – Why my answer code is wrong?

Q: By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

My Code:

x = 1
y = 2
ans = 0
evens = []
while x <= 4000000:
    ans = x + y
    x = y
    y = ans
    if ans % 2 == 0:
        evens.append(ans)
print(sum(evens))

My result is 4613730 while it should be 4613732.
What am I don’t understand here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use print(evens) inside loop to see what you missed. Now, first 2 is not printed.

First even, 2, is not inserted to the evens, so one of ways to correct the code is inserting 2 into evens right before starting a loop. There might be many ways to solve this issue.

x = 1
y = 2
ans = 0
evens = [2]
while x <= 4000000:
    ans = x + y
    x = y
    y = ans
    if ans % 2 == 0:
        evens.append(ans)
    print(evens) # to debug what are in in a 'evens' list
print(sum(evens)) 
# 4613730
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading