简体   繁体   中英

Project Euler #2 in Python

Background

I am stuck on this problem:

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, ...

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

I tried to discover if the issue was my Fibonacci number generator, the code which gets the even numbers, or even the way that I add the numbers to no avail.

Code

I decided to store the numbers in lists. Here, I create them.

list_of_numbers = [] #Holds all the fibs
even_fibs = [] #Holds only even fibs

Then, I created my generator. This is a potential area of issues .

x,y = 0,1 #sets x to 0, y to 1
while x+y <= 4000000: #Gets numbers till 4 million
    list_of_numbers.append(y)
    x, y = y, x+y #updates the fib sequence

Then, I created some code to check if a number is even, and then add it to the even_fibs list. This is another weakpoint in the code.

coord = 0
for number in range(len(list_of_numbers)):
    test_number = list_of_numbers [coord]

    if (test_number % 2) == 0:
        even_fibs.append(test_number)
    coord+=1

Lastly, I display the information.

print "Normal:  ", list_of_numbers #outputs full sequence
print "\nEven Numbers: ", even_fibs #outputs even numbers
print "\nSum of Even Numbers:  ", sum(even_fibs) #outputs the sum of even numbers

Question

I know that this is a terrible way to ask a question, but what is wrong? Please don't give me the answer - just point out the problematic section.

You're stopping when the sum of the next two values in the sequence is greater than 4,000,000. You're meant to consider all values in the sequence up to 4,000,000.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM