Search code examples
pythonfibonaccimemoization

Project Euler #2 - Python v3.2.3


I'm having trouble with problem 2 on Project Euler. The objective is to find the sum of the even-valued terms in the Fibonacci sequence whose values do not exceed four million. For some reason, I keep getting 0 as my output. What am I doing wrong?

total = 0
count = 0
term = 0
fibonacciMemo = {0:0, 1:1}

def main ():
    term = fibonacci (count)
    while (term <= 4000000):
        if (term % 2 == 0):
            total += term
        count += 1

def fibonacci (n):
    if not n in fibonacciMemo:
        fibonacciMemo [n] = fibonacci (n - 1) + fibonacci (n - 2)
    return fibonacciMemo [n]

print (total)

Solution

  • Some issues:

    • You're never calling the main function. You must explicitly call it for it to be executed.

    • The assignments to variables term, count, total in main will not write to the global variables. Instead, distinct local variables with the same names will be created, and the global variables will still have the value 0 even after main is called.

      One way to fix this is to add the line global term, count, total in main. But this is bad design. Much better is to remove the global variables (make them all local to main), and have main return the value of total. Then print(main()) will show the result.

    • You only call fibonacci once in main - you'll want to put that inside the loop. Otherwise the loop will run infinitely since term is never updated.