Right, here is my attempt at problem 2 of project euler.

*Problem: //projecteuler.net/index.php?section=problems&id=2*

*source: //bitbucket.org/TWith2Sugars/project-euler/changeset/3ec9f237dbb9*

def fib(n): evenSum, a, b = 0, 0, 1 while a < n: a, b = b, a+b if b % 2 == 0: evenSum += b return evenSum; result = fib(4000000) print(result)

## Update:

Thanks to Mohammad’s advice the code has been update to avoid pointlessly assigning variables.

def fib(n): evenSum, a, b = 0, 1, 2 while a < n: if b % 2 == 0: evenSum += b a, b = b, a+b return evenSum; result = fib(4000000) print(result)

## 6 Comments

Please include links to Project Euler problem in question.

Short and elegant.

I noticed that if a and b are switched to 1,2, you will get the wrong answer. Lines 5 and 6 should come before line 4.

This example was found in the python docs.

If this is the one you are talking about, it doesn’t have the check for even numbers. By not writing it before line 4 you are ignoring the input values since you are changing the variables before testing. In the case of (0,1) it doesn’t matter, but for (1,2), it does.

The link I’m talking about – //docs.python.org/tutorial/modules.html 🙂

That’s the one (although I am actually using python 3.x)