5

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.

2
  • 2
    for number in range(len(list_of_numbers)):test_number = list_of_numbers [coord] can be translated to for test_number in list_of_numbers. Then you can get rid of coord. Commented Mar 14, 2013 at 21:01
  • +1 for "Please don't give me the answer - just point out the problematic section." Commented Mar 24, 2013 at 12:32

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much - it has been bugging me for a while.
Another way of saying this is [1, 4000000).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.