Reputation: 153
Looking for some help with this project Euler question: By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
I am sure there are other, simpler ways to do this but I am just starting out! I have managed to get the code to output the sum of the even terms of the fibonacci sequence, but I have no idea how to set the output limit to four million (I have just set the range 1 - 10 for testing). Is there anyway to do this with the current code I have written, rather than starting again?
def fibonacci(n):
if n==0:
return 0
elif n==1 or n==2:
return 1
elif n>2:
return (fibonacci(n-1)+fibonacci(n-2))
fib_list=[fibonacci(n) for n in range (1, 10) if fibonacci(n)%2==0]
fib_even=sum(fib_list)
print(fib_list)
print(fib_even)
Upvotes: 3
Views: 2068
Reputation: 17322
you can use the built-in functions sum
and filter
:
def fib(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
sum(filter(lambda x: x%2==0, fib(4_000_000)))
output:
4613732
the fib
function will generate all the Fibonacci numbers while the filter
function will filter out those numbers that are not even, and finally, the sum
built-in function will add all the even numbers
Upvotes: 1
Reputation: 251
Here is my solution:
def fibonacci():
sequence = [1, 2]
total = 0
while sequence[-1] < 4000000:
if sequence[-1] % 2 == 0:
total += sequence[-1]
sequence.append(sequence[-1] + sequence[-2])
print(total)
The check on the last element in the list ensures that it does not run over 4 million. This is also what sgfw meant by their response. I am not sure how you would go about implementing that for a list comprehension - it wouldn't be my first choice for solving this problem.
Upvotes: 1
Reputation: 312
A "while" loop may be more suitable for this problem than a list comprehension. It may even be easiest to use a "while True" loop with a conditional "break" statement.
Upvotes: 0