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这个要多多理解