Algorithm learned with Python 13th: Tower of Hanoi

#Algorithm learned in Python

Introduction

Implement the basic algorithm in Python to deepen your understanding of the algorithm. The 13th edition deals with the Tower of Hanoi.

Tower of Hanoi

The Tower of Hanoi is well known. The rules are shown below. ・ Completed by moving from end to end in the same shape ・ You cannot move on something smaller than yourself

Implementation

Here, the program showing the movement procedure at that time by moving between the three axes and inputting only the number of blocks to be handled is shown below. I tried to visualize it, but since it is a little different from the essence of knowing the algorithm, I will show only the part I tried.

code

hanoi.py


"""
2020/12/31
@Yuya Shimizu

Tower of Hanoi
"""

#Arguments: number of blocks, move source, move destination, via
def hanoi(n, source, destination, via):
    if n > 1:
        hanoi(n-1, source, via, destination)  #Recursion
        print(source + '->' + destination)
        hanoi(n-1, via, destination, source)  #Recursion
    else:
        print(source + '->' + destination)

n = int(input('Number of steps in Hanoi>> '))
hanoi(n, 'a', 'c', 'b')
output
Number of steps in Hanoi>> 3     #Enter 3
a->c
a->b
c->b
a->c
b->a
b->c
a->c
code

hanoi_v.py


"""
2020/12/31
@Yuya Shimizu

Tower of Hanoi (visualization)
"""

def tower(n):
    result = ""
    for i in range(1,n+1):
        #Even rows
        if i %2 == 0:
            result += f"|  {' '*(n-i+1)}{'- '*(i//2)}{'- '*(i//2)}\t|  "
            result += f"{' '*(n-i+1)}{'- '*(i//2)}{'- '*(i//2)}\t|"
            result += f"  {' '*(n-i+1)}{'- '*(i//2)}{'- '*(i//2)}\t|  "

        #Odd lines
        else:
            result += f"|  {' '*(n-i+1)}{'- '*(i//2)}- {'- '*(i//2)}\t|  "
            result += f"{' '*(n-i+1)}{'- '*(i//2)}- {'- '*(i//2)}\t|"
            result += f"  {' '*(n-i+1)}{'- '*(i//2)}- {'- '*(i//2)}\t|  "

        result += "\n"
    return result

#Arguments: number of blocks, move source, move destination, via
def hanoi(n, source, destination, via):
    if n > 1:
        hanoi(n-1, source, via, destination)  #Recursion
        print(source + '->' + destination)
        hanoi(n-1, via, destination, source)  #Recursion
    else:
        print(source + '->' + destination)

#n = int(input('Number of steps in Hanoi>> '))
#hanoi(n, 'a', 'c', 'b')
print(tower(4))
output
|     -    |     -    |     - 	 |  
|    - -   |    - -   |    - - 	 |  
|   - - -  |   - - -  |   - - -  |  
|  - - - - |  - - - - |  - - - - |  

For the time being, I made only the figures that were all arranged. I will try it again when I feel like it. The visualization program is introduced by @shiracamus in the comment section.

Impressions

I learned the algorithm to solve the Tower of Hanoi, and learned that the processing time required at this time increases exponentially. He thought he could even visualize it, but realized that it would take some time, and I think it's a bit off in terms of learning algorithms, and I'll try to visualize it when I feel like it. According to other people's articles, it seems that python also has a module that even visualizes, and it seems that the existing Hanoi Tower program can be handled by the following operations.

$ pip install k-peg-hanoi
$ hanoi 4 4

Visualization in my own program is introduced by @shiracamus in the comment section.

References

Introduction to algorithms starting with Python: Standards and computational complexity learned with traditional algorithms Written by Toshikatsu Masui, Shoeisha

Recommended Posts

Algorithm learned with Python 13th: Tower of Hanoi
Algorithm learned with Python 8th: Evaluation of algorithm
Algorithm learned with Python 10th: Binary search
Algorithm learned with Python 5th: Fibonacci sequence
Algorithm learned with Python 9th: Linear search
Algorithm learned with Python 7th: Year conversion
Algorithm learned with Python 4th: Prime numbers
Algorithm learned with Python 19th: Sorting (heapsort)
Algorithm learned with Python 6th: Leap year
Algorithm learned with Python 12th: Maze search
Algorithm learned with Python 11th: Tree structure
Algorithm learned with Python 16th: Sorting (insertion sort)
Algorithm learned with Python 14th: Tic-tac-toe (ox problem)
Algorithm learned with Python 15th: Sorting (selection sort)
Algorithm learned with Python 17th: Sorting (bubble sort)
Algorithm learned with Python 18th: Sorting (stack and queue)
Implementation of Dijkstra's algorithm with python
Algorithm learned with Python 2nd: Vending machine
1. Statistics learned with Python 1-3. Calculation of various statistics (statistics)
Algorithm learned with Python 3rd: Radix conversion
1. Statistics learned with Python 1-2. Calculation of various statistics (Numpy)
Challenge the Tower of Hanoi with recursion + stack
"Principle of dependency reversal" learned slowly with Python
[Python3] Dijkstra's algorithm with 14 lines
1. Statistics learned with Python 2. Probability distribution [Thorough understanding of scipy.stats]
Tower of Hanoi-Recursive / Non-recursive (Python edition)
[Python] Object-oriented programming learned with Pokemon
Getting Started with Python Basics of Python
Perceptron learning experiment learned with Python
Python data structures learned with chemoinformatics
Life game with Python! (Conway's Game of Life)
Efficient net pick-up learned with Python
10 functions of "language with battery" python
1. Statistics learned with Python 1-1. Basic statistics (Pandas)
4th night of loop with for
Recursion challenge to Tower of Hanoi
Coexistence of Python2 and 3 with CircleCI (1.0)
Bookkeeping Learned with Python-The Flow of Bookkeeping-
Basic study of OpenCV with Python
March 14th is Pi Day. The story of calculating pi with python
[Python] Reactive Extensions learned with RxPY (3.0.1) [Rx]
Basics of binarized image processing with Python
[Examples of improving Python] Learning Python with Codecademy
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
Execute Python script with cron of TS-220
Conditional branching of Python learned by chemoinformatics
Check the existence of the file with python
Python algorithm
Clogged with python update of GCP console ①
Search the maze with the python A * algorithm
Easy introduction of speech recognition with Python
Source code of sound source separation (machine learning practice series) learned with Python
UnicodeEncodeError struggle with standard output of python3
Drawing with Matrix-Reinventor of Python Image Processing-
Recommendation of Altair! Data visualization with Python
Let's develop an investment algorithm with Python 1
Comparison of matrix transpose speeds with Python
Non-recursive implementation of extended Euclidean algorithm (Python)
I tried it with SymPy Live, Wolfram Alpha and google with reference to "Algorithm learned with Python 4th: Prime numbers".
Web application production course learned with Flask of Python Part 2 Chapter 1 ~ JSON exchange ~
Deep Learning from scratch The theory and implementation of deep learning learned with Python Chapter 3