本系列为加州伯克利大学著名 Python 基础课程 CS61A 的课堂笔记整理,全英文内容,文末附词汇解释。
目录
01-1 Functions as Argument Values
01-2 Functions as Return Values
02 Environments of Higher-Order Functions
01 Higher-Order Functions
A function that takes a function as an argument value or returns a function as a return value.
① Express general methods of computation
② Remove repetition(重复) from programs
③ Separate concerns among functions
01-1 Functions as Argument Values

"""Generalization."""
from math import pi, sqrt
def area_square(r):
return r * r
def area_circle(r):
return r * r * pi
def area_hexagon(r):
return r * r * 3 * sqrt(3) / 2
"""Generalize Formal Paraments."""
from math import pi, sqrt
def area(r, shape_constant):
assert r > 0, 'A length must be positive'
return r * r * shape_constant ※
def area_square(r):
return area(r, 1)
def area_circle(r):
return area(r, pi)
def area_hexagon(r):
return area(r, 3 * sqrt(3) / 2)

"""Generalize Functions"""
def natural(k):
return k
def cube(k):
return pow(k, 3)
def pi_term(k):
return 8 / mul(4 * k - 3, a * k - 1)
def summation(n, term):
"""Sum the first n terms of a sequence.
>>> summation(5, cube)
225
"""
total, k = 0, 1
while k <= n:
total, k = total + term(k), k + 1
return total
def sum_naturals(n):
total, k = 0, 1
while k <= n:
total, k = total + k, k + 1
return total
def sum_cubes(n):
total, k = 0, 1
伯克利CS61A高阶函数课堂笔记

最低0.47元/天 解锁文章
1338

被折叠的 条评论
为什么被折叠?



