编辑浏览 UCB CS61A HW01 Q3: Make Repeater

文章讨论了一个Python编程问题,要求实现make_repeater函数,该函数接收一个函数func和一个整数n,返回一个新的函数,这个新函数会连续应用funcn次。错误的尝试包括不正确的compose1和accumulate函数组合使用,以及对整数对象的错误调用。正确解决方案是使用lambda表达式保持函数的延迟计算特性。
摘要由CSDN通过智能技术生成

来看一个案例:
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函数时,

  1. 调用make_repeater函数,
    1.1 调用accumulator函数,k=1
    1.1.1 调用term函数,即increment λ函数,x=k=1,return value = term(1)=increment(1)=2

据此分析:参数

正解:
定义add_three函数时,

  1. 调用make_repeater函数,
    1.1 调用accumulator函数,k=1
    1.1.1 调用term函数,即lambda x: func。⚠️ x=k=1,但是lambda表达式仍然是一个函数,当期被命名并调用参数时才会计算出结果,如此便避免了随参数k递增而得变化的结果值
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值