# HANOR recursive function recursive chain expression yl embodiment COUNT = 0 DEF Hanoi (n-, the src, DST, MID): Global COUNT IF n-==. 1 : Print ( " {}: {} -> {} " .format ( . 1 , the src, DST)) COUNT + =. 1 the else : Hanoi (n- -1 , the src, MID, DST) Print ( " {}: {} -> {} " .format (n-, the src, DST)) COUNT + . 1 = Hanoi (n- -1 , MID, DST, the src) Hanoi ( . 3, " A " , "C","B") print(count)
Only consider the relationship with the n 1-n times times
The following excerpt from a network (a model for future learning. The real unique skills)
import turtle class Stack: def __init__(self): self.items = [] def isEmpty(self): return len(self.items) == 0 def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): if not self.isEmpty(): return self.items[len(self.items) - 1] def size(self): return len(self.items) defdrawpole_3 (): # Draw Tower of Hanoi Poles T = turtle.Turtle () t.hideturtle () DEF drawpole_1 (K): t.up () t.pensize ( 10 ) t.speed ( 100 ) T. Goto ( 400 * (. 1-K), 100 ) t.down () T. Goto ( 400 * (. 1-K), -100 ) T. Goto ( 400 * (. 1-K) -20, -100 ) T. GOTO ( 400 * (. 1-K) +20, -100 ) drawpole_1 (0) # draw Tower of Hanoi Poles [0] drawpole_1 (. 1) # draw Tower of Hanoi Poles [. 1] drawpole_1 (2) #Draw Tower of Hanoi Poles [2] DEF creat_plates (n): # producing n disks Plates = [turtle.Turtle () for I in Range (n)] for I in Range (n): Plates [I]. up () Plates [I] .hideturtle () Plates [I] .shape ( " Square " ) Plates [I] .shapesize ( 1,8 I) Plates [I] .goto ( -400, -90 * + 20 is I) Plates [I] .showturtle () return Plates DEF pole_stack (): # producing poles stack poles = [stack () for Iin Range (. 3 )] return Poles DEF moveDisk (Plates, Poles, FP, TP): # the poles [fp] to the top plate plates [mov] From poles [fp] to move Poles [TP] MOV = poles [fp] .peek () Plates [MOV] .goto ((FP -1) * 400,150 ) Plates [MOV] .goto ((TP -1) * 400,150 ) L = Poles [TP] .size () # determines the movement in the end portion height (on the plate just above the uppermost original) plates [MOV] .goto ((. 1-TP) * 400, * 20 is -90 + L) DEF moveTower (plates, Poles, height, fromPole, toPole, withPole): # recursive discharge tray IF height> =. 1 : moveTower (plates, Poles, height -1,fromPole,withPole,toPole) moveDisk(plates,poles,fromPole,toPole) poles[toPole].push(poles[fromPole].pop()) moveTower(plates,poles,height-1,withPole,toPole,fromPole) myscreen=turtle.Screen() drawpole_3() n=int(input("请输入汉诺塔的层数并回车:")) plates=creat_plates(n) poles=pole_stack() for i in range(n): poles[0].push(i) moveTower(plates,poles,n,0,2,1) myscreen.exitonclick()