 johnpaulada
1/17/2017 - 7:39 AM

## Solves https://projecteuler.net/problem=2 with Python in FP style. Gets the the sum of all even numbers in the fibonacci sequence from 1 to

Solves https://projecteuler.net/problem=2 with Python in FP style. Gets the the sum of all even numbers in the fibonacci sequence from 1 to the specified limit.

``````# Creates a function that will filter a list using the given function
def filterer(filter_fn):
return lambda l: filter(filter_fn, l)

# Creates a function that will reduce a list using the given function
def reducer(reduce_fn):
return lambda l: reduce(reduce_fn, l)

# Creates a fibonacci function with the first two numbers already set
def fib_init(first, second):

# The fibonacci function that generates a list of the numbers until the given limit
def fib(limit):

# The recursive function that generates the list
def actual_fib(current, next):
if current < limit:
previous = current
current  = next
next  = previous + current
return [current] + actual_fib(current, next)
else:
return []

return actual_fib(first, second)
return fib

# Function that returns true if argument is even
even = lambda x: x % 2 == 0

# Function that returns true if argument is odd
odd = lambda x: x % 2 != 0

# Function that adds its two arguments
sum = lambda x, y: x + y

# Creates a filter function for even numbers
filter_even = filterer(even)

# Creates a filter function for odd numbers
filter_odd = filterer(odd)

# Creates a function that takes the sum of every element in the list
summer = reducer(sum)

# Creates the fibonacci function
fib_to_limit = fib_init(1, 2)

# Sum of the even fibonacci numbers from 1 to n
def sum_even_fib(n):
return summer(filter_even(fib_to_limit(n)))

# Sum of the odd fibonacci numbers from 1 to n
def sum_odd_fib(n):
return summer(filter_odd(fib_to_limit(n)))

limit = input("Enter upper limit: ")

print("Sum of all evens: ")
print(sum_even_fib(limit))

print("Sum of all odds: ")
print(sum_odd_fib(limit))
``````