关于python:我遇到的一个非常奇怪的python的问题-cs61a-lab02

7次阅读

共计 1673 个字符,预计需要花费 5 分钟才能阅读完成。

上面是源代码

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

这样写的话

>>> 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

这样的谬误

然而如果改成这样

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 是能够拿到的,然而却不能够间接用,最最最奇怪的是,看到答案这么写


    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 既能够拿到,也能够间接用,我人都傻了

正文完
 0