Skip to content

Instantly share code, notes, and snippets.

@travisby
Created February 7, 2013 03:05
Show Gist options
  • Save travisby/4728074 to your computer and use it in GitHub Desktop.
Save travisby/4728074 to your computer and use it in GitHub Desktop.
Memoized fibonacci sequence in python
"""
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 term
"""
memory = {
0: 0,
1: 1,
}
def fib(n):
if n not in memory:
memory[n] = fib(n - 1) + fib(n - 2)
return memory[n]
# fib(38) > 4*10^6
# we start at 2 so we get the same pattern...
print(
sum(
[
y for y in
[fib(x) for x in range(2, 38)]
if not y % 2 and y < 4000000
]
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment