其他分享
首页 > 其他分享> > CS61A 学习笔记 lecture 4 Higher-Order Functions

CS61A 学习笔记 lecture 4 Higher-Order Functions

作者:互联网

质数、因数

  1. is_prime(n)函数,判断n是否为质数
  2. smallest_factor(n)函数,返回n大于1的最小因数(speed up!)
  3. 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. 一些术语和注释
  1. domain,定义域
  2. range,值域
  3. codomain,上域(大概意思应该是:domain是codomain的子集)
  4. 文档注释
2. 两条原则
  1. 函数应该只做一件明确的事(复杂的文档注释说明函数做得太多)
  2. DRY(Don’t Repeat Yourself),不要重复,出现重复的代码块建议重构(refactoring),将重复代码块替换成一个单独的函数
summation举例, 函数作为参数
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))

标签:Functions,return,函数,CS61A,add,smallest,factor,lecture,def
来源: https://www.cnblogs.com/ikventure/p/14813503.html