# 阶段四:高阶函数 阅读以及完成本部分内容可以帮助你有效减少代码冗余。 让你完成更为优雅的代码 各位要记住的是 # 代码首先是给人看的 机器看的永远只是你的机器码。 可参考教程 [Lambda](https://zhuanlan.zhihu.com/p/80960485) # Lambda 介绍 Lambda 表达式是通过指定两件事来评估函数的表达式:参数和返回表达式。 请尝试阅读以下英文表格,对比函数与 lambda 表达式的不同 # Lambda 实验 以下代码 python 会显示什么?通过对这些代码的实验,加深你对代码的学习 提示:当你对解释器输入 x 或 x=none 时什么都没有 ```python >>> lambda x: x # A lambda expression with one parameter x ______ >>> a = lambda x: x # Assigning the lambda function to the name a >>> a(5) ______ >>> (lambda: 3)() # Using a lambda expression as an operator in a call exp. ______ >>> b = lambda x: lambda: x # Lambdas can return other lambdas! >>> c = b(88) >>> c ______ >>> c() ______ >>> d = lambda f: f(4) # They can have functions as arguments as well. >>> def square(x): ... return x * x >>> d(square) ______ ``` ```python >>> higher_order_lambda = lambda f: lambda x: f(x) >>> g = lambda x: x * x >>> higher_order_lambda(2)(g) # Which argument belongs to which function call? ______ >>> higher_order_lambda(g)(2) ______ >>> call_thrice = lambda f: lambda x: f(f(f(x))) >>> call_thrice(lambda y: y + 1)(0) ______ >>> print_lambda = lambda z: print(z) # When is the return expression of a lambda expression executed? >>> print_lambda ______ >>> one_thousand = print_lambda(1000) ______ >>> one_thousand ______ ``` # 任务 P9:我们发现以下两个函数看起来实现的非常相似 ```python def count_factors(n): """Return the number of positive factors that n has. >>> count_factors(6) 4 # 1, 2, 3, 6 >>> count_factors(4) 3 # 1, 2, 4 """ i, count = 1, 0 while i <= n: if n % i == 0: count += 1 i += 1 return count def count_primes(n): """Return the number of prime numbers up to and including n. >>> count_primes(6) 3 # 2, 3, 5 >>> count_primes(13) 6 # 2, 3, 5, 7, 11, 13 """ i, count = 1, 0 while i <= n: if is_prime(i): count += 1 i += 1 return count def is_prime(n): return count_factors(n) == 2 # only factors are 1 and n ``` 你可以通过一个函数 count_cond 来接受一个含有两个参数的函数 condition(n, i) `count_cond` 返回一个单参数函数,它在调用时 `n` 计算从 1 到 `n` 满足的所有数字 `condition`。 ```python def count_cond(condition): """Returns a function with one parameter N that counts all the numbers from 1 to N that satisfy the two-argument predicate function Condition, where the first argument for Condition is N and the second argument is the number from 1 to N. >>> count_factors = count_cond(lambda n, i: n % i == 0) >>> count_factors(2) # 1, 2 2 >>> count_factors(4) # 1, 2, 4 3 >>> count_factors(12) # 1, 2, 3, 4, 6, 12 6 >>> is_prime = lambda n, i: count_factors(i) == 2 >>> count_primes = count_cond(is_prime) >>> count_primes(2) # 2 1 >>> count_primes(3) # 2, 3 2 >>> count_primes(4) # 2, 3 2 >>> count_primes(5) # 2, 3, 5 3 >>> count_primes(20) # 2, 3, 5, 7, 11, 13, 17, 19 8 """ "*** YOUR CODE HERE ***" ```