来看一个案例:
Implement the function make_repeater
so that make_repeater(func, n)(x)
returns func(func(...func(x)...))
, where func
is applied n
times.
For an extra challenge, try defining make_repeater
using compose1
and your accumulate
function in a single one-line return statement.
案例来源:UCB US61A: Python > HW 02 > Q3
from operator import add
identity = lambda x: x
increment = lambda x: x + 1
def compose1(func1, func2):
def f(x):
return func1(func2(x))
return f
def accumulate(combiner, base, n, term):
result, k = base, 1
while k <= n:
result, k = combiner(result, term(k)), k + 1
return result
def make_repeater(func, n):
"""Return a function that computes the nth application of func.
>>> add_three = make_repeater(increment, 3)
>>> add_three(5)
8
"""
"*** YOUR CODE HERE ***"
# return accumulate(compose1, func, n, func) #k=1时func应用了两次❌
# return accumulate(compose1, func, n, identity) #term=identity,随参数k递增取值变化❌
# 报错代码示例:return accumulate(compose1, identity, n, func) #term=func,随参数k递增取值变化❌
return accumulate(compose1, identity, n, lambda x: func) # 正解
1. Use Ok to test your code
查看报错定位及提示
% python3 ok -q make_repeater
--------
Doctests for make_repeater
>>> from hw02 import *
>>> add_three = make_repeater(increment, 3)
>>> add_three(5)
Traceback (most recent call last):
File "/.../hw02.py", line xxx, in f
return func1(func2(x))
TypeError: 'int' object is not callable
# Error: expect
# 8
# but got
# Traceback (most recent call last):
# ...
# TypeError: 'int' object is not callable
--------
在执行add_three(5)
测试代码的过程中,执行make_repeater
,再执行compose1
函数中的func1(func2(x))
语句时,int
型对象未被调用;
即指整数型参数5
未被调用;
但是,compose1
函数中定义了
2. Edit code in Online Python Tutor
查看报错前代码执行步骤
On line Python Tutor
执行至阻断语句,提示:
TypeError: 'int' object is not callable
定义add_three
函数时,
- 调用
make_repeater
函数,
1.1 调用accumulator
函数,k=1
1.1.1 调用term
函数,即increment λ
函数,x=k=1,return value = term(1)=increment(1)=2
据此分析:参数
正解:
定义add_three
函数时,
- 调用
make_repeater
函数,
1.1 调用accumulator
函数,k=1
1.1.1 调用term
函数,即lambda x: func
。⚠️ x=k=1,但是lambda表达式仍然是一个函数,当期被命名并调用参数时才会计算出结果,如此便避免了随参数k递增而得变化的结果值