patternpythonModerate
Python Solution for Project Euler #2 (Fibonacci Sums)
Viewed 0 times
fibonacciprojectforpythoneulersolutionsums
Problem
I'm a fairly new programmer (just started yesterday!). I decided to tackle Project Euler #2 today, as I did #1 yesterday without many problems. I came up with what seems to me to be a working solution, but I feel like I did it in an exceedingly ugly way. Could anyone suggest improvements to my code and/or logic?
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.
I just sort of used my
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.
fib = 1
fib2 = 2
temp = 0
total = 0
while temp <=4000000:
temp = fib2
if temp % 2 == 0:
total += temp
temp = fib + fib2
fib = fib2
fib2 = temp
print totalI just sort of used my
temp variable as a holding ground for the results, and then juggled some variables around to make it do what I wanted... Seems like quite a mess. But it does result in 4613732, which seems to be correct!Solution
I would use separately Fibonacci generator
And
def even_fib(limit):
a, b = 0, 1
while a < limit:
if not a % 2:
yield a
a, b = b, a + bAnd
sum function to calculate sum of itemsprint sum(even_fib(4000000))Code Snippets
def even_fib(limit):
a, b = 0, 1
while a < limit:
if not a % 2:
yield a
a, b = b, a + bprint sum(even_fib(4000000))Context
StackExchange Code Review Q#9830, answer score: 15
Revisions (0)
No revisions yet.