Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am currently working on Project Euler problem #2 which requires you to print the sum of all even fibonacci numbers below 4 million.

I just recently learned about generators and from my understanding they are used to decrease memory consumption by generating values on the fly (and not storing them in a huge list).

Does this still work when used in a for loop or will it just generate all values, store them in a list and then loop through them?

for n in some_generator(): pass

In my specific case the code looks like this:

def fibonacci(n): # yields all fibonacci numbers below n
    second_last_n = 0
    last_n = 1
    while (last_n < n):
        current_n = second_last_n + last_n
        second_last_n = last_n
        last_n = current_n
        yield current_n

def filter_even(nums): # yields all numbers in nums (a generator) which are even
    for n in nums:
        if (n % 2 == 0):
            yield n
share|improve this question
up vote 3 down vote accepted

It's weird that the fibonacci() generates a sequence that starts with 1, 2, 3, 5, 8, …. Conventionally, the Fibonacci sequence starts with either 0, 1, 1, 2, 3, 5, 8, … or 1, 1, 2, 3, 5, 8, ….

A purer approach would be to use [itertools.takewhile()] in conjunction with an infinite generator.

You should also take advantage of parallel assignment.

The fibonacci() generator would look like this:

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

filter_even() is fine. You could also just write a generator expression instead.

from itertools import takewhile

print(sum(n for n in takewhile(lambda n: n < 4000000, fibonacci()) if n % 2 == 0))
share|improve this answer
    
...The comment # yields all fibonacci numbers below n is misleading.... sorry, I just fixed the code to use a while loop instead of a for loop, so the comment should be right.. – Dominik Schmidt Apr 17 '15 at 20:05
1  
In the future, please refrain from modifying code in the question after posting. – 200_success Apr 17 '15 at 20:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.