下面的赋值取自here
Q5. Define the repeated function from Homework 2 by calling reduce with compose1 as the first argument. Add only a single expression to the starter implementation below:
def square(x):
return x*x
def compose1(f, g):
"""Return a function of x that computes f(g(x))."""
return lambda x: f(g(x))
from functools import reduce
def repeated(f, n):
"""Return the function that computes the nth application of f, for n>=1.
f -- a function that takes one argument
n -- a positive integer
>>> repeated(square, 2)(5)
625
>>> repeated(square, 4)(5)
152587890625
"""
assert type(n) == int and n > 0, "Bad n"
return reduce(compose1, "*** YOUR CODE HERE ***" )
为了完成这个任务,我想了解g
绑定到什么?f
绑定到square
函数
首先,
repeated(f, 4)
应该返回什么?你知道吗对任意
arg
调用时将返回f(f(f(f(arg))))
的函数。你知道吗因此,如果您想用
compose1
构建它,您需要返回compose1(compose1(compose1(f, f), f), f)
或compose1(f, compose1(f, compose1(f, f)))
。你知道吗现在,看看^{} 做了什么,弄清楚它每次都会传递给
compose1
什么。很明显,iterable
参数必须以f
本身开始或结束。但是你还想要什么来确保你得到两个可接受的结果中的一个呢?你知道吗同时,在每个对
compose1
的调用中,除了最后一个,两个参数中的一个必须是repeated
函数的f
,而另一个将是另一个对compose1
的调用的结果。(当然,最后一次,它们都是f
)找出它们中的哪一个是f
,哪一个是g
,以及如何让reduce
为每一个传递正确的值,就解决了问题。你知道吗相关问题 更多 >
编程相关推荐