汉诺塔内存分析(python)

Python029

汉诺塔内存分析(python),第1张

def hanoi(n,a,b,c):

     if n>0:

     hanoi(n-1,a,c,b)

     print("moving from %s to %s" %(a,c))

     hanoi(n-1,b,a,c)

hanoi(3,"a","b","c")

输出显示:

moving from a to c : moving from a to b:moving from c to b:moving from a to c:moving from b to a:moving from b to c : moving from a to c

1、首先,函数中有两个情况:(1)如只有一个盘子,则不需要利用B座,直接将盘子从A移动到C,在移动过程中可以不利用B座,(2)将最大盘子上面的n-1个盘子通过C为辅助盘移到B,B上的n-1个盘子由A为辅助盘移动C。(n-1个盘子的移动泽根据递归来实现)汉诺塔问题的递归终止条件即是A座上只有一个盘子。

2、其次,输出移动次数时,要求的宽度为4个字符,右对齐用{:>4}去实现。