名称“g”绑定到哪个对象?

2024-04-26 20:38:17 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的赋值取自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函数


Tags: ofthefromreducereturnthatdeffunction
1条回答
网友
1楼 · 发布于 2024-04-26 20:38:17

首先,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为每一个传递正确的值,就解决了问题。你知道吗

相关问题 更多 >