Berkeley CS 61A Lecture 9

http://inst.eecs.berkeley.edu/~cs61a/sp18/

CS 61A LECTURE 9

Function Abstractions

在这里插入图片描述

Choosing names

在这里插入图片描述

Which values deserve a name

在这里插入图片描述

Testing

在这里插入图片描述
the greatest common divisor of two integers m and n:

#test
python -m doctest ex.py
def gcd(m, n):
	"""Returns the largest k that divides both m and n

	k, m, n are all positive integers.

	>>> gcd(12, 8)
	4
	>>> gcd(16, 12)
	4
	>>> gcd(16, 8)
	8
	>>> gcd(2, 16)
	2
	>>> gcd(5,5)
	5
	"""
	if m == n:
		return m
	elif m < n:
		return gcd(n, m)
	else:
		return gcd(m-n, n)

Function currying

用于创建一个已经设置好了一个或多个参数的函数

在这里插入图片描述

def curry2(f):
	def g(x):
		def h(y):
			return f(x, y)
		return h
	return g
>>> from operator import add
>>> add(2, 3)
5
>>> m = curry2(add)
>>> add_three = m(3)
>>> add_three(2)
5
>>> add_three(2010)
2013
>>> curry2 = lambda f:lambda x: lambda y: f(x, y)
>>> m = curry2(add)
>>> m(2)(3)
5

Decorators

def trace1(fn):
	"""Returns a version of fn 
	that first prints before it is called.

	fn - a function of 1 argument
	"""
	def traced(x):
		print('Calling', fn, 'on argument', x)
		return fn(x)
	return traced

@trace1
def square(x):
	return x * x

@trace1
def sum_square_up_to(n):
	k = 1
	total = 0
	while k <= n:
		total, k = total + square(k), k+1
	return total
>>> square(12)
Calling <function square at 0x000001AE37DB6620> on argument 12
144

>>> sum_square_up_to(5)
Calling <function sum_square_up_to at 0x000002325A706730> on argument 5
Calling <function square at 0x000002325A706620> on argument 1
Calling <function square at 0x000002325A706620> on argument 2
Calling <function square at 0x000002325A706620> on argument 3
Calling <function square at 0x000002325A706620> on argument 4
Calling <function square at 0x000002325A706620> on argument 5
55
# @trace1 等价于 
square = trace1(square)

在这里插入图片描述

What would python print

在这里插入图片描述

在这里插入图片描述

horse这个要多多理解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值