Python中的函数组合
先决条件: reduce(),lambda
函数组合是组合两个或多个函数的方式,使得一个函数的输出成为第二个函数的输入,依此类推。例如,假设有两个函数“F”和“G”,它们的组合可以表示为 F(G(x)),其中“x”是参数,G(x)函数的输出将成为 F 的输入()函数。
例子:
# Function to add 2
# to a number
def add(x):
return x + 2
# Function to multiply
# 2 to a number
def multiply(x):
return x * 2
# Printing the result of
# composition of add and
# multiply to add 2 to a number
# and then multiply by 2
print("Adding 2 to 5 and multiplying the result with 2: ",
multiply(add(5)))
输出:
Adding 2 to 5 and multiplying the result with 2: 14
解释
首先在输入 5 上调用add()
函数。 add()
将 2 加到输入上,输出为 7,作为multiply()
的输入,将其乘以 2,输出为 14
实现组合的更好方法
有一种更好的方法来实现函数的组合。我们可以创建一个可以组合任意两个函数的特殊函数。
# Function to combine two
# function which it accepts
# as argument
def composite_function(f, g):
return lambda x : f(g(x))
# Function to add 2
def add(x):
return x + 2
# Function to multiply 2
def multiply(x):
return x * 2
# Composite function returns
# a lambda function. Here add_multiply
# will store lambda x : multiply(add(x))
add_multiply = composite_function(multiply, add)
print("Adding 2 to 5 and multiplying the result with 2: ",
add_multiply(5))
输出:
Adding 2 to 5 and multiplying the result with 2: 14
组成N个函数
我们可以通过修改上述方法来组合任意数量的函数。
# Function to combine two
# function which it accepts
# as argument
def composite_function(f, g):
return lambda x : f(g(x))
# Function to add 2
def add(x):
return x + 2
# Function to multiply 2
def multiply(x):
return x * 2
# Function to subtract 2
def subtract(x):
return x - 1
# Composite function returns
# a lambda function. Here
# add_subtract_multiply will
# store lambda x : multiply(subtract(add(x)))
add_subtract_multiply = composite_function(composite_function(multiply,
subtract),
add)
print("Adding 2 to 5, then subtracting 1 and multiplying the result with 2: ",
add_subtract_multiply(5))
输出:
Adding 2 to 5, then subtracting 1 and multiplying the result with 2: 12
现在我们将通过使用 functools 库中的 reduce()函数将我们的 composite_function 修改为一个可以组合任意数量的函数而不是两个函数的函数。
# importing reduce() from functools
from functools import reduce
# composite_function accepts N
# number of function as an
# argument and then compose them
def composite_function(*func):
def compose(f, g):
return lambda x : f(g(x))
return reduce(compose, func, lambda x : x)
# Function to add 2
def add(x):
return x + 2
# Function to multiply 2
def multiply(x):
return x * 2
# Function to subtract 2
def subtract(x):
return x - 1
# Here add_subtract_multiply will
# store lambda x : multiply(subtract(add(x)))
add_subtract_multiply = composite_function(multiply,
subtract,
add)
print("Adding 2 to 5, then subtracting 1 and multiplying the result with 2: ",
add_subtract_multiply(5))
输出:
Adding 2 to 5, then subtracting 1 and multiplying the result with 2: 12
解释reduce()
函数从 *func 获取前两个函数并使用compose()
组合它们,然后将第三个函数组合到前一个组合函数,依此类推。这里首先组合multiply()
和subtract()
(multiply(subtract(x))) 然后组合 add() (multiply(subtract(add(x))))。