1. 程式人生 > >python第二天:遞歸函數(漢諾塔)

python第二天:遞歸函數(漢諾塔)

mage -- def code class pre 技術分享 style .py

 1 #hanoi.py
 2 def hanoi(n,x,y,z):
 3     if n==1:
 4         print(x,"-->",z)
 5     else:
 6         hanoi(n-1,x,z,y)
 7         print(x,"-->",z)
 8         hanoi(n-1,y,x,z)
 9 hanoi(2,"X","Y","Z")
10 print("----------")
11 hanoi(3,"X","Y","Z")

結果如下:

技術分享圖片

python第二天:遞歸函數(漢諾塔)