注:本文不涉及Hanoi塔算法原理,只提供Python代码实现
1. 基本代码
def Hanoi_1(n,X,Y,Z):def move(X,Z):print(f' Move from {X} to {Z}')if n == 1:move(X,Z)else:Hanoi_1(n-1,X,Z,Y)move(X,Z)Hanoi_1(n-1,Y,X,Z)Hanoi_1(4,'X','Y','Z')
输出结果:
2. 增强代码:能够输出具体步骤、当前状态及总步数
class Hanoi_2():def __init__(self,n,X,Y,Z) -> None:import numpy as npself.X_ring = list(np.arange(1,n+1))self.Y_ring = []self.Z_ring = []self.total_num = 0print(f"The original status is: X:{self.X_ring}\tY:{self.Y_ring}\tZ:{self.Z_ring}\n\n")def move(self,a,b,a_ring,b_ring):print(f'Move {a_ring[0]} from {a} to {b}')b_ring.insert(0,a_ring[0])a_ring.pop(0)self.total_num += 1print(f'The current status is: X:{self.X_ring}\tY:{self.Y_ring}\tZ:{self.Z_ring}')def action(self,n,X,Y,Z):if n == 1:self.move(X,Z,eval(f'self.{X}_ring'),eval(f'self.{Z}_ring'))else:self.action(n-1,X,Z,Y)self.move(X,Z,eval(f'self.{X}_ring'),eval(f'self.{Z}_ring'))self.action(n-1,Y,X,Z)def cal(self):print(f'The total num of moving is:{self.total_num} ')num = 4a = Hanoi_2(num,'X','Y','Z')a.action(num,'X','Y','Z')a.cal()
输出结果: