4.7 python函数递归 汉诺塔
代码:
def hanno(n,A,B,C):
global step
if n==1:
print('{}->{}'.format(A,C))
step +=1
else:
hanno(n-1,A,C,B)
print('{}->{}'.format(A,C))
step += 1
hanno(n - 1,B,A,C)
return step
step=0
print(hanno(3,'A','B','C'))
运行结果:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4bf9143b1a84b87306d2dbda5836b39a.png)
备注:
运用全局变量step计算步数