Skip to content

Instantly share code, notes, and snippets.

@walkerh
Last active January 20, 2024 23:00
Show Gist options
  • Save walkerh/c755981342b61d52846a65522d55543c to your computer and use it in GitHub Desktop.
Save walkerh/c755981342b61d52846a65522d55543c to your computer and use it in GitHub Desktop.
fib
import itertools
def fibonacci_generator():
a, b = 1, 2
while True:
yield a
a, b = b, a + b
def calculate_even_fibonacci_sum(limit):
even_fibs = filter(lambda n: n%2 == 0, fibonacci_generator())
even_fibs_less_than_4m = itertools.takewhile(lambda x: x <= limit, even_fibs)
even_sum = sum(even_fibs_less_than_4m)
return even_sum
# Set the limit to 4 million
limit = 4000000
# Calculate and print the sum
result = calculate_even_fibonacci_sum(limit)
print(f"The sum of even Fibonacci numbers less than {limit} is: {result}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment