我正在通过 Berkely 非正式地学习 Python 课程 CS61A,我完全被一项简单的作业难住了,该作业要求我在提供的模板的最后只提供一个表达式。这是问题代码:
# 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
我已经尝试了一切来完成这项工作。在我看来,这个 return stmt 应该这样做:
return reduce(compose1, range(n))
但我什至没有接近。Compose1 需要两个参数 (f, g),它们都应该是函数。但是当 return 语句调用 'compose1' 时,'compose1' 使用 '0' 代表 'f' 和 'n' 代表 'g'。但是 'f' 和 'g' 应该是函数调用--'square'
我错过了什么。