下面是源代碼python
def cycle(f1, f2, f3): """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 ***" def h1(n): def h2(x): while n > 3: x = f3(f2(f1(x))) n -= 3 if n == 0: x =x elif n == 1: x = f1(x) elif n == 2: x = f2(f1(x)) elif n == 3: x = f3(f2(f1(x))) return x return h2 return h1
這樣寫的話ide
>>> 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)
而後會報一個
UnboundLocalError: local variable 'n' referenced before assignment函數
這樣的錯誤code
可是若是改爲這樣it
def cycle(f1, f2, f3): """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 ***" def h1(num): def h2(x): n = num while n > 3: x = f3(f2(f1(x))) n -= 3 if n == 0: x =x elif n == 1: x = f1(x) elif n == 2: x = f2(f1(x)) elif n == 3: x = f3(f2(f1(x))) return x return h2 return h1
就沒有問題,說明在外面函數中定義的這個num
是能夠拿到的,可是卻不能夠直接用,最最最奇怪的是,看到答案這麼寫io
def ret_fn(n): def ret(x): i = 0 while i < n: if i % 3 == 0: x = f1(x) elif i % 3 == 1: x = f2(x) else: x = f3(x) i += 1 return x return ret return ret_fn
這樣寫沒有問題,說明這個n既能夠拿到,也能夠直接用,我人都傻了function