LearnFrenzy
Sign in Take a free test

Iterators and Generators · Iterators and Generators Coding Problems · Question 2

Fibonacci numbers with a generator in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Write a generator that yields Fibonacci numbers below a limit, and use it to print the series below 100 and the count of even terms below 4,000,000.

Solution
main.py Run
def fibonacci(limit):
    a, b = 0, 1
    while a < limit:
        yield a
        a, b = b, a + b

print(list(fibonacci(100)))
print(sum(1 for n in fibonacci(4_000_000) if n % 2 == 0))

Output Verified by running it on Python 3

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
12

The generator keeps just two numbers in memory; the counting generator expression never builds a list.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links