Project Euler Problem 2

(Spoilers below!)

Problem 2:

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.

Having negative indices proves to be pretty useful! The ‘-1’ element of a list returns the last element of the list. This can be used to access the last and second to last elements of fiblist without having to keep track of the size of the list.

(Currently this solution works, but can definitely be made more efficient- I’ll update if I made changes)

fibList = [1,1]
fibSum = 0
while fibList[-1] <= 4000000:
	num = fibList[-1] + fibList[-2]
	if num % 2 is 0:
		fibSum += num
	fibList.append(num)
print fibSum