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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!