"""Returns a function that is itself a higher-order function. >>> def add1(x): ... return x + 1 >>> def times2(x): ... return x * 2 >>> def add3(x): ... return x + 3 >>> my_cycle = cycle(add1, times2, add3) >>> identity = my_cycle(0) >>> identity(5) 5 >>> add_one_then_double = my_cycle(2) >>> add_one_then_double(1) 4 >>> do_all_functions = my_cycle(3) >>> do_all_functions(2) 9 >>> do_more_than_a_cycle = my_cycle(4) >>> do_more_than_a_cycle(2) 10 >>> do_two_cycles = my_cycle(6) >>> do_two_cycles(1) 19 """
"*** YOUR CODE HERE ***"
deffinal(n):
defvalue(x):
result = x
function = [f1,f2,f3]
for i inrange(n):
result = function[i%3](result)
return result
return value
return final
Pure function and Non-pure function
Pure functions: applying them has no effects beyond returning a value. Moreover, a pure function must always return the same value when called twice with the same arguments.
Non-pure functions: In addition to returning a value, applying a non-pure function can generate side effects, which make some change to the state of the interpreter or computer
eg: The print function returns Nonebut prints some value to the console
Lambda Expressions
Lambda表达式就可以不用为函数起名字
1 2
lambda x : f(g(x)) "A function that takes x and returns f(g(x))"
Compound Lambda expressions are illegible
Lambda expression returns a function
Python3数学函数
(x>y)-(x<y):如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1
exp(x):返回e的x次幂
fabs(x):以浮点数形式返回数字的绝对值,如math.fabs(-10) 返回10.0
modf(x):返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。
1 2 3 4 5 6 7 8
import math x = 3.75 # 调用 modf fractional_part, integral_part = math.modf(x)
"""Returns whether or not n has two digits in row that are the number 8. >>> double_eights(1288) True >>> double_eights(880) True >>> double_eights(538835) True >>> double_eights(284682) False >>> double_eights(588138) True >>> double_eights(78) False >>> # ban iteration >>> from construct_check import check >>> check(LAB_SOURCE_FILE, 'double_eights', ['While', 'For']) True """
"""Return a function can_reach(x, y, limit) that returns whether some call expression containing only f, g, and x with up to limit calls will give the result y. >>> up = lambda x: x + 1 >>> double = lambda y: y * 2 >>> can_reach = make_onion(up, double) >>> can_reach(5, 25, 4) # 25 = up(double(double(up(5)))) True >>> can_reach(5, 25, 3) # Not possible False >>> can_reach(1, 1, 0) # 1 = 1 True >>> add_ing = lambda x: x + "ing" >>> add_end = lambda y: y + "end" >>> can_reach_string = make_onion(add_ing, add_end) >>> can_reach_string("cry", "crying", 1) # "crying" = add_ing("cry") True >>> can_reach_string("un", "unending", 3) # "unending" = add_ing(add_end("un")) True >>> can_reach_string("peach", "folding", 4) # Not possible False """
defcan_reach(x, y, limit):
if limit < 0:
returnFalse
elif x == y:
returnTrue
else:
return can_reach(f(x), y, limit - 1) or can_reach(g(x), y, limit - 1)