CS61A_lab02
1 def cycle(f1, f2, f3): 2 """Returns a function that is itself a higher-order function. 3 4 >>> def add1(x): 5 ... return x + 1 6 >>> def times2(x): 7 ... return x * 2 8 >>> def add3(x): 9 ... return x + 3 10 >>> my_cycle = cycle(add1, times2, add3) 11 >>> identity = my_cycle(0) 12 >>> identity(5) 13 5 14 >>> add_one_then_double = my_cycle(2) 15 >>> add_one_then_double(1) 16 4 17 >>> do_all_functions = my_cycle(3) 18 >>> do_all_functions(2) 19 9 20 >>> do_more_than_a_cycle = my_cycle(4) 21 >>> do_more_than_a_cycle(2) 22 10 23 >>> do_two_cycles = my_cycle(6) 24 >>> do_two_cycles(1) 25 19 26 """ 27 "*** YOUR CODE HERE ***" 28 def combine(n): 29 def F(x): 30 p=n//3 31 q=n%3 32 for i in range(p): 33 x=f3(f2(f1(x))) 34 if q==0: 35 return x 36 elif q==1: 37 return f1(x) 38 else: 39 return f2(f1(x)) 40 return F 41 return combine
评点:
最精妙的地方就在于for循环赋值x【 x=f3(f2(f1(x))) 】,直接将所有大于3的情况都变为3以内的情况,然后再来列举考虑。
1 def lambda_curry2(func): 2 """ 3 Returns a Curried version of a two-argument function FUNC. 4 >>> from operator import add, mul, mod 5 >>> curried_add = lambda_curry2(add) 6 >>> add_three = curried_add(3) 7 >>> add_three(5) 8 8 9 >>> curried_mul = lambda_curry2(mul) 10 >>> mul_5 = curried_mul(5) 11 >>> mul_5(42) 12 210 13 >>> lambda_curry2(mod)(123)(10) 14 3 15 """ 16 "*** YOUR CODE HERE ***" 17 return lambda x :lambda y: func(x,y)
题目描述:
Let a path be some sequence of directions, starting with S
for start, and followed by a sequence of U
and D
s representing up and down directions along the path. For example, the path SUDDDUUU
represents the path up
, down
, down
, down
, up
, up
, up
.
Your task is to implement the function both_paths
, which prints out the path so far (at first just S
), and then returns two functions, each of which keeps track of a branch down or up. This is probably easiest to understand with an example, which can be found in the doctest of both_paths
as seen below.
代码:
def both_paths(sofar="S"): """ >>> up, down = both_paths() S >>> upup, updown = up() SU >>> downup, downdown = down() SD >>> _ = upup() SUU """ "*** YOUR CODE HERE ***" print(sofar) def up(): return both_paths(sofar+'U') def down(): return both_paths(sofar+'D') return up, down
lambda函数与currying小结
一、例子
1.
1 >>> def compose1(f, g): 2 return lambda x: f(g(x))
等同于
1 def compose1(f,g): 2 def F(x): 3 return f(g(x)) 4 return F
不同于
1 def compose1(f): 2 def F(g): 3 return f(g) 4 return F
第三段代码等同于
1 def compose1(f): 2 return lambda g: f(g)
2.
1 >>> def curried_pow(x): 2 def h(y): 3 return pow(x, y) 4 return h
等同于
1 def curried_pow(x): 2 return lambda y: pow(x,y)
3.
1 def curry2(f): 2 def g(x): 3 def h(y): 4 return f(x,y) 5 return h 6 return g
等同于
1 def curry2(f): 2 return lambda x: lambda y: f(x,y)
二、总结
lambda表达式其实就是def的省略版本,所以lambda表达式也就是一个函数。不同在于,def能够自己定义函数的名称,而lambda表达式不可以定义名称
冒号之前的变量就是def方式的变量,而冒号后面的操作就是def定义的函数中的操作。
看多个嵌套函数的时候,不应该首先看多个嵌套函数的具体定义,而是应该像编译器一样,先看函数的返回值。由返回值来引导自己看函数的步骤。