ajaykarpur
ajaykarpur

Reputation: 318

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)

Upvotes: 1

Views: 527

Answers (3)

interjay
interjay

Reputation: 110182

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.

Upvotes: 6

ch3ka
ch3ka

Reputation: 12158

It is because you never call main or fibonacci. You just assign

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

and then

print (total)

If you want to execute main, you have to explicitly call it, e.g. by putting main() in front of print (total)

You have another problem in your code. You attempt to increment the global variable total from within a function. That won't work, unless you declare total global to this function. Do so by putting global total in the function before you first use total. Same problem with count and term. And it seems you have a problem in your control flow, too. This won't generate the right answer.

Upvotes: 4

Nathan Hughes
Nathan Hughes

Reputation: 96444

Add this line to the bottom of your script:

if __name__ == "__main__":
    main()

That will call main() when you run the file as a Python script.

BTW there is a much better solution to the Project Euler problem, you can generate the even Fibonacci terms directly instead of filtering. Make a habit of looking for smart solutions now, or you will hit a wall when the problems get challenging.

Upvotes: 2

Related Questions