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://img-blog.csdnimg.cn/20210407095038928.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0FuXzAzMzA=,size_16,color_FFFFFF,t_70)
备注:
运用全局变量step计算步数