python 使用FP样式的Python解决https://projecteuler.net/problem=2。获取斐波纳契序列中从1到1的所有偶数的总和

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用FP样式的Python解决https://projecteuler.net/problem=2。获取斐波纳契序列中从1到1的所有偶数的总和相关的知识,希望对你有一定的参考价值。

# 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))

以上是关于python 使用FP样式的Python解决https://projecteuler.net/problem=2。获取斐波纳契序列中从1到1的所有偶数的总和的主要内容,如果未能解决你的问题,请参考以下文章

FP-growth算法思想和其python实现

如何在win10中卸载python软件包

FP-Growth算法之FP-tree的构造(python)

FP-Growth算法之频繁项集的挖掘(python)

Python文件操作

Python fp