CS61A 学习笔记 lecture 4 Higher-Order Functions
- 0-15min,QA,以hog为例,提出pair-programming,可使用vscode的live share扩展
- 15-30min,上节课的factor prime函数
- 30min后,开始正题higher order functions
质数、因数
is_prime(n)
函数,判断n是否为质数smallest_factor(n)
函数,返回n大于1的最小因数(speed up!)print_factors(n)
函数,对n进行因数分解
# Prime numbers
def is_prime(n):
"""Return True iff N is prime.
return n > 1 and smallest_factor(n) == n
def smallest_factor(n):
"""Returns the smallest value k>1 that evenly divides N."""
k = 2
while k <= n:
if n % k == 0:
return k
k += 1
def print_factors(n):
"""Print the prime factors of N."""
k = 2
while n > 1:
d = smallest_factor(n)
print(d)
n = n // d # or n //= d
高阶函数
1. 一些术语和注释
- domain,定义域
- range,值域
- codomain,上域(大概意思应该是:domain是codomain的子集)
- 文档注释
2. 两条原则
- 函数应该只做一件明确的事(复杂的文档注释说明函数做得太多)
- DRY(Don’t Repeat Yourself),不要重复,出现重复的代码块建议重构(refactoring),将重复代码块替换成一个单独的函数
summation举例, 函数作为参数
- 函数是第一类值(first-class values),可以作为变量传递给函数,也可以作为函数的返回值。求和举例将传入term函数,计算平方和、立方和、级数等。
- lambda函数
def summation(N, term):
k = 1
sum = 0
while k <= N:
sum += term(k)
k += 1
return sum
def sum_squares(N):
def square(x):
return x*x
return summation(N, square)
# or
def sum_squares(N):
return summation(N, lambda x: x*x)
def summations():
print(summation(10, lambda x: x**3)) # Sum of cubes
print(summation(10, lambda x: 1 / x)) # Harmonic series
print(summation(10, lambda k: x**(k-1) / factorial(k-1))) # Approximate e**x
Functions that return functions, 函数作为返回值
def add_func(f, g):
"""Return function that returns F(x)+G(x) for argument x."""
def adder(x): #
return f(x) + g(x) # or return lambda x: f(x) + g(x)
return adder #
h = add_func(abs, neg)
print(h(-5))
# Generalizing still more:
def combine_funcs(op):
def combined(f, g):
def val(x):
return op(f(x), g(x))
return val
return combined
# Now, can define instead
add_func = combine_funcs(add)
h = add_func(abs, neg)
print(h(-5))
-
函数组合在环境中的执行过程
-
这样的条件函数是不存在的