Problem 2 "Even Fibonacci Number"
The Fibonacci sequence terms are the sum of the previous two terms. If the first two terms are 1, 2, then the first 10 terms are: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of even-valued terms with a sequence term value of 4 million or less.
Python
fibs = [1, 2]
while True:
next_fib = sum(fibs[-2:])
if(next_fib <= 4000000):
fibs.append(next_fib)
else:
break
result = 0
for i in fibs:
if(i % 2 == 0):
result += i
print result
print result == 4613732
result
4613732
True
It seems that the result part can be written concisely by using the list comprehension notation.
Python
result = sum([i for i in fibs if i % 2 == 0])
Recommended Posts