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
Pimgd
22.5k5 gold badges68 silver badges144 bronze badges
asked Apr 17, 2015 at 19:32
\$\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))
answered Apr 17, 2015 at 20:03
\$\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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.