在Python3

时间:2016-07-15 01:25:18

标签: python python-3.x global-variables

如何修改main函数中的全局变量?我设置了一个全局变量ADDITION并在函数中修改它。然后,我尝试在main中修改它,但似乎我失败了。

ADDITION = 0

def add(a, b):
    global ADDITION
    ADDITION = ADDITION + 1
    return a+b

def fib_classic(n):
    if(n <= 1):
            return n

    else:
            return add(fib_classic(n-2) , fib_classic(n-1))


def fib_closed(n):
    fib = (math.pow(1+math.sqrt(5),n) - (1-math.pow(math.sqrt(5),n)))/(math.pow(2,n)*math.sqrt(5))
    return math.floor(fib)


def fib_classic(n):
    if(n <= 1):
            return n

    else:
            return add(fib_classic(n-2) , fib_classic(n-1))


def fib_loop(n):
    a = 0
    b = 1

    if(n <= 1):
            return n

    else:
            for i in range(0, n-1):
                    c = b
                    b = add(a, b)
                    a = c
            return b


def fib_mem(n):
    global FIB_DIC
    if(n in FIB_DIC):
            return FIB_DIC[n]

    else:
            if(n <= 1):
                    FIB_DIC[n] = n

            else:
                    FIB_DIC[n] = add(fib_mem(n-1), fib_mem(n-2))

            return FIB_DIC[n]

def main():

    for i in range(0,36):
            global ADDITION
            print("Computing the {0}th Fibonacci Number:".format(i))
            print("The closed form finds:", end=" "); print(fib_closed(i))
            print("The recursive definition finds:", end=" "); print(fib_classic(i))
            print("Additions needed for recursive definition:", end=" "); print(ADDITION)
            ADDITIION = 0
            print(ADDITION) # not 0
            print("The loop definition finds:", end=" "); print(fib_loop(i))
            print("Additions needed for loop definition:", end=" "); print(ADDITION)
            ADDITION = 0
            print("The memoization definition finds:", end=" "); print(fib_mem(i))
            print("Additions needed for memoization definition:", end=" "); print(ADDITION)
            print("--------------------")

2 个答案:

答案 0 :(得分:2)

main()中有拼写错误:

        ADDITIION = 0

应该是

        ADDITION = 0

答案 1 :(得分:0)

您认为您的代码以何种方式运行?也许首先尝试简化它。此代码的行为符合预期:

ADDITION = 0

def modify():
    global ADDITION
    ADDITION = ADDITION + 1

def main():
    global ADDITION
    print("Initial value: {}".format(ADDITION))
    modify()
    print("Subsequent value: {}".format(ADDITION))
    ADDITION = 0
    print("Zero'd out: {}".format(ADDITION))
    modify()
    print("Modified again: {}".format(ADDITION))

if __name__ == '__main__':
    main()

# Output:
# Initial value: 0
# Subsequent value: 1
# Zero'd out: 0
# Modified again: 1