python recursion - Tower of Hanoi

The legend of the Tower of Hanoi

The French mathematician Edouard Lucas once wrote an ancient Indian legend: In the holy temple of Benares (in northern India), the center of the world, three jeweled needles were inserted into a brass plate. When Brahma , the main god of Hinduism, created the world, he wore 64 pieces of gold from large to small on one of the needles, which is the so-called Tower of Hanoi. Day or night, there is always a monk moving these pieces of gold according to the following rule: move only one piece at a time, and no matter which needle it is on, the small piece must be on top of the larger piece. The monks prophesied that when all the gold pieces were moved from the pin Brahma wore to the other pin, the world would be destroyed in a thunderclap, and the Brahma pagoda , temples, and sentient beings would also perish.

  No matter how credible this legend is, if you consider moving 64 pieces of gold from one needle to another, and always keep the top small and bottom large in order .
  How many moves does this require? A recursive approach is required here. Suppose there are n pieces, and the number of moves is f(n). Obviously f(1)=1, f(2)=3, f(3)=7, and f(k+1)=2*f(k)+ 1. It is not difficult to prove f(n)=2^n-1 afterwards . When n=64,
If every second, how long would it take? There are 31,536,000 seconds in 365 days in a normal year, and 31,622,400 seconds in 366 days in a leap year. The average year is 31,556,952 seconds. Calculate:
  18446744073709551615 seconds
This shows that it takes more than 584.554 billion years to remove   these gold flakes , while the earth has existed for only 4.5 billion years, and the life expectancy of the solar system is said to be tens of billions of years. It has really passed 584.554 billion years, not to mention the solar system and the Milky Way, at least all life on earth, together with Brahma pagodas, temples, etc., have long since vanished.

 

python tower of hanoi

#Recursive algorithm of the function Tower of Hanoi 
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 bottom last plate from x to z 
        hanoi(n-1,y,x,z) #Move n -1 plates on y to z 
n=int(input( ' Please enter the number of layers of Tower of Hanoi: ' ))
hanoi (n, ' x ' , ' y ' , ' z ' )

》Please enter the number of layers of the Tower of Hanoi: 3 
x --> z
x --> y
z --> y
x --> z
y --> x
y --> z
x --> z

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325211981&siteId=291194637