汉诺塔问题 ← Python代码

【汉诺塔问题算法代码】

tot=0
def move(n,a,b,c):
    global tot
    if n==0:
        return    
    
    move(n-1,a,c,b)
    tot=tot+1    
    print('{}:{} -> {}'.format(tot,a,c))
    move(n-1,b,a,c)
    
move(3,'a','b','c')


【注意事项】
特别注意,Python在函数内部使用全局变量的一种常用方法:
即首先需在函数外部给一个变量赋初值,然后在函数内部用关键字global将此变量声明为全局变量。而且,不能有形如global a=5 的语句,而需为:
global a
a=5

例如,由 Python - How to use a global variable in a function - Mkyong.com 给出的例子可验证:

# Correct
a = 10
 
def updateGlobal():
    global a
    a = 5
 
updateGlobal()
print(a)  # 5



【参考文献】
https://mkyong.com/python/python-how-to-use-a-global-variable-in-a-function/

猜你喜欢

转载自blog.csdn.net/hnjzsyjyj/article/details/121432388
今日推荐