Last active
August 29, 2015 13:55
-
-
Save emadshaaban92/8722026 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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)) |
You can use itertools.count
or xrange
instead of implementing numbers
@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 :)
@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
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.