Python algorithm design source code: https://github.com/MakerChen66/Python3Algorithm
Copyright statement: Originality is not easy, this article prohibits plagiarism, reprinting, infringement must be investigated!
Table of contents
1. Tower of Hanoi
Towers of Hanoi: Simple and classic algorithm with an interesting recursive solution.
The Tower of Hanoi (also known as the Tower of Hanoi) is an educational toy that originated from an ancient Indian legend. When Brahma created the world, he made three diamond pillars. On one pillar, 64 gold discs were stacked in order of size from bottom to top. Brahma ordered Brahmin to rearrange the discs on another pillar in order of size from below. And it is stipulated that the disk cannot be enlarged on the small disk, and only one disk can be moved between the three pillars at a time. So how to do it with Python?
Let's imagine if we want to move the largest disk to the rightmost column. We need to move the other disks except the largest disk to the middle pillar first. So the problem becomes how to move N-1 disks to the middle pillar. Then we thought of the recursive method.
Move N discs from the left peg to the right peg:
- Recursively move N-1 discs from the left column to the middle column
- Move the largest disk from the left column to the right column
- Recursively move N-1 discs from the middle column to the right column
Python algorithm implementation:
def hanoi(height, left='left', right='right', middle='middle'):
if height:
hanoi(height - 1, left, middle, right)
print(left, '=>', right)
hanoi(height - 1, middle, right, left)
hanoi(3)
Output result:
2. Source code download
Python algorithm design source code download:
- GitHub download link: Portal
- Link to the original text: Read the original text
3. Author Info
Author: Xiaohong's Fishing Daily, Goal: Make programming more interesting!
Original WeChat public account: " Xiaohong Xingkong Technology ", focusing on algorithms, crawlers, websites, game development, data analysis, natural language processing, AI, etc., looking forward to your attention, let us grow and code together!
Copyright Note: This article prohibits plagiarism and reprinting, and infringement must be investigated!