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)
Some issues:
You’re never calling the
mainfunction. You must explicitly call it for it to be executed.The assignments to variables
term,count,totalinmainwill 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 value0even aftermainis called.One way to fix this is to add the line
global term, count, totalinmain. But this is bad design. Much better is to remove the global variables (make them all local tomain), and havemainreturn the value oftotal. Thenprint(main())will show the result.You only call
fibonaccionce inmain– you’ll want to put that inside the loop. Otherwise the loop will run infinitely sincetermis never updated.