Skip to content

Instantly share code, notes, and snippets.

@emadshaaban92
Last active August 29, 2015 13:55
Show Gist options
  • Save emadshaaban92/8722026 to your computer and use it in GitHub Desktop.
Save emadshaaban92/8722026 to your computer and use it in GitHub Desktop.
#! /usr/bin/env python3
from functools import lru_cache
from itertools import count, takewhile
numbers = count(1)
MAX = 4000000
@lru_cache(maxsize=None)
def fib(n) :
if n < 3 :
return 1
else :
return fib(n-2) + fib(n-1)
fibs = (fib(x) for x in numbers)
even_fibs = (x for x in fibs if x % 2 == 0)
even_fibs_under_max = takewhile(lambda x : x < MAX, even_fibs)
print(sum(x for x in even_fibs_under_max))
@emad-elsaid
Copy link

lru_cache is really useful.
your thinking is very organized you took it as small steps and finished them separately and depending on each other
i like it.

@mtayseer
Copy link

You can use itertools.count or xrange instead of implementing numbers

@emadshaaban92
Copy link
Author

@blazeeboy Thanks :). And thanks for your idea, I've learned a lot from the other solutions so far .

@mtayseer range must have upper limit and I wanted to make a generic solution, you're right itertools.count is what I should use but I forgot about it , Thanks for reminding me :)

@emadshaaban92
Copy link
Author

@mtayseer In fact even_fibs_under_max can be simpler using itertools.takewhile, I noticed that while solving the same problem using Opa :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment