The first problem encountered in learning python: the implementation of the Hannota problem. First of all, I don't know what is the Hannota problem, and then I don't know how to realize it. So Baidu, the results are as follows:
Hanoi Tower: The Hanoi Tower (also known as the Tower of Hanoi) problem is a puzzle toy originating from an ancient Indian legend. When Maharaja Brahma created the world he made three diamond pillars, and on one pillar 64 golden discs were stacked in order of size from bottom to top. Brahma ordered the Brahmins to rearrange the disks in order of size from the bottom on another pillar. And it was stipulated that the discs could not be enlarged on the smaller discs, and that only one disc at a time could be moved between the three pillars
Method I:
def move(n,a,b,c) # n=2 if n==1 : # Skip print a,'-->',c return None move(n-1,a,c,b) # n=2, after executing n-1, move(n-1,a,c,b)->move(1,a,c,b),jump to if, execute print: a-->b print a,'-->',c # Execute print, where a and c are the parameters a and c of the defined function, and print the result: a-->c move(n-1,b,a,c) # n=1 ,after executing n-1, jump to if, execute print, at this time, a=b,c=c, the result is: b-->c move(2,'a','b','c')
Method II:
def printMove(fr,to): print 'move from ' + str(fr) + ' to ' + str(to) def Towers(n,fr,to,spare): if n == 1: printMove(fr,to) else: Towers(n-1,fr,spare,to) Towers(1,fr,to,spare) Towers(n-1,spare,to,fr)
Method Three:
def hanoi(n,x,y,z): if n==1: print(x,'-->',z) else: hanoi(n-1,x,z,y)# Move the first n-1 plates from x to y hanoi(1,x,y,z)# Move the last plate at the bottom from x to z # hanoi(n-1,y,x,z)# Move the n-1 plates on y to z n=int(input('Please enter the number of floors in Hanno's Tower:')) hanoi(n,'x','y','z')
To summarize:
# Notes on the thoughts of Hannota
# Recognize Hannukah's Tower Goal: Move N plates from column A to column C
# The idea of recursion is to break this goal down into three sub-goals
# Sub-goal 1: Move the first n-1 plates from a to b.
# Sub-objective 2: Move the last plate at the bottom from a to c
# Sub-goal 3: Move n-1 plates from b to c.
# And then each subgoal is a separate game of Hannukah, which allows you to continue to decompose the goal until N is 1