2
\$\begingroup\$

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
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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))
\$\endgroup\$
2
  • \$\begingroup\$ ...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.. \$\endgroup\$ Commented Apr 17, 2015 at 20:05
  • 1
    \$\begingroup\$ In the future, please refrain from modifying code in the question after posting. \$\endgroup\$ Commented Apr 17, 2015 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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