Python summing itertools.count?
Question: I'm having some trouble with the itertools.count function, and I don't quite
understand what it does. I expect the code below to accomplish [Project Euler
problem 2](http://projecteuler.net/problem=2).

I know that I could write this with a simple while loop, but is there a way to
do it with a list comprehension? This code just freezes as I guess it's going
to go infinity with count(). I would have hoped it would stop after x > MAX,
but I know that won't happen. Is there a way to stop count in a generator
expression like below?

    
    
    def fib(n):
        if (n <= 1): return 1
        else: return fib(n-1) + fib(n-2)
    
    
    MAX = 4000000
    
    infiniteFib = (fib(x) for x in count())
    
    s = (x for x in infiniteFib if x < MAX and x % 2 == 0)
    
    print sum(s)
    


Answer: You could use
[`takewhile`](http://docs.python.org/2/library/itertools.html#itertools.takewhile):

    
    
    >>> from itertools import count, takewhile, imap
    >>> sum(x for x in takewhile(lambda x: x < 4000000, imap(fib, count())) if x % 2 == 0)
    4613732
    

