私は非公式にバークレーでPythonコースCS61Aを行っていますが、提供されたテンプレートの最後に1つの式のみを提供する必要がある1つの単純な割り当てに完全に困惑しています。問題のコードは次のとおりです。
# HW 4 Q5. (fall 2012)
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 ***" )
repeated(square, 2)(5) # Sample run
私はこれを機能させるためにあらゆることを試みました。このreturnstmtはそれを行う必要があるように私には思えます:
return reduce(compose1, range(n))
しかし、私は近くにさえいません。Compose1は2つの引数(f、g)を取り、これらは両方とも関数である必要があります。ただし、returnステートメントが「compose1」を呼び出す場合、「compose1」は「f」に「0」を使用し、「g」に「n」を使用します。ただし、「f」と「g」は「square」と呼ばれる関数である必要があります。
私は何が欠けていますか。