在函数中调用2个函数 [英] call 2 functions in a function
问题描述
问题如下:
编写一个函数compose,它以两个函数作为参数,我们称它们为 Fa
和 Fb
,并返回一个函数 Fres
,这意味着来自另一个函数的outdata是indata第一个,例如: Fres(x)= Fa(Fb(x))
。
运行示例:
>>> def multiply_five(n):
... return n * 5
...
>>> def add_ten(x):
... return x + 10
...
>>> composition = compose(multiply_five,add_ten)
>>>组成(3)
65
>>> another_composition = compose(add_ten,multiply_five)
>>> another_composition(3)
25
因此,据我了解,如果我发送3函数compose将花费3 + 10 = 13
,然后将结果发送到它将执行的乘法函数中:13 * 5 witch是65.
这是我迄今为止编写的代码:
def multiply_five(n):
返回n * 5
def add_ten(x):
return x + 10
def compose(func1,func2):
def comp(arg):
返回func2(arg)
返回func1(comp (arg))
我得到编译错误,并尝试了一些不同的方法:
Traceback(最近一次调用最后一次):
文件< pyshell#3>,第1行,在< module>
composition = compose(multiply_five,add_ten)
文件C:\Users\Jim\Desktop\tdp002\5h.py,第10行,编写
返回func1 (comp(arg))
NameError:name'arg'未定义
您不想调用 func1
或 func2
你只是想返回一个将调用它们的函数。
def compose(func1,func2 ):
def _(* args,** kw):
返回func1(func2(* args,** kw))
返回_
您也可以使用 lambda
表达式来创建组合函数。
def compose(func1,func2):
返回lambda * args,** kw:func1(func2(* args,** kw))
The problem is as follows below:
Write a function compose that takes two functions as argument, we call them Fa
and Fb
, and returns a function, Fres
, that means that outdata from the other function is indata to the first, ex: Fres(x) = Fa(Fb(x))
.
run example:
>>> def multiply_five(n):
... return n * 5
...
>>> def add_ten(x):
... return x + 10
...
>>> composition = compose(multiply_five, add_ten)
>>> composition(3)
65
>>> another_composition = compose(add_ten, multiply_five)
>>> another_composition(3)
25
So as I understand this if I send in 3 the function compose will take 3+10 = 13 after that send that result into the multiply function it will do: 13*5 witch is 65. this is the code I've written so far:
def multiply_five(n):
return n*5
def add_ten(x):
return x+10
def compose(func1, func2):
def comp(arg):
return func2(arg)
return func1(comp(arg))
I get compile error, and I've tried some different approaches:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
composition = compose(multiply_five, add_ten)
File "C:\Users\Jim\Desktop\tdp002\5h.py", line 10, in compose
return func1(comp(arg))
NameError: name 'arg' is not defined
You don't want to call either func1
or func2
yet; you just want to return a function that will call them both.
def compose(func1, func2):
def _(*args, **kw):
return func1(func2(*args, **kw))
return _
You could also just use a lambda
expression to create the composed function.
def compose(func1, func2):
return lambda *args, **kw: func1(func2(*args, **kw))
这篇关于在函数中调用2个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!