[Python] Learning Note 1

Tower of Hanoi

py


def hanoinoto(hanoi, n):
    """Tower of Hanoi display"""
    print('------', n)
    for stack in hanoi:
        print('#', ''.join(stack))

N = 3  #Number of disks

#State of the disk at three positions
hanoi = [list('4321')[-N:], [], []]
hanoinoto(hanoi, 0)  #Initial state display

#Move all discs
for n in range(1, 2**N):
    i = (n & (n - 1)) % 3  #Move source (bit operation)
    j = ((n | (n - 1)) + 1) % 3  #Move destination (bit operation)
    c = hanoi[i].pop()  #Pop from position i
    hanoi[j].append(c)  #Append to position j(push)
    hanoinoto(hanoi, n)

Execution result

------ 0 # 321 # # ------ 1 # 32 # # 1 ------ 2 # 3 # 2 # 1 ------ 3 # 3 # 21 # ------ 4 # # 21 # 3 ------ 5 # 1 # 2 # 3 ------ 6 # 1 # # 32 ------ 7 # # # 321

Recommended Posts

[Python] Learning Note 1
Note: Python
python learning
Python note
Python study note_002
Note: Python Decorator
Python programming note
Python learning notes
python learning output
Python study note_004
Python learning site
Python learning day 4
Python Deep Learning
Python study note_003
Python learning (supplement)
Deep learning × Python
[Note] openCV + python
Python beginner's note
python learning notes
"Python Machine Learning Programming" Summary Note (Jupyter)
Python class (Python learning memo ⑦)
Learning Python with ChemTHEATER 03
"Object-oriented" learning with python
Python module (Python learning memo ④)
[Note] future sentence ~ Python ~
Reinforcement learning 1 Python installation
[Note] File reading ~ Python ~
Learning Python with ChemTHEATER 05-1
Python: Deep Learning Practices
Python ~ Grammar speed learning ~
Python: Unsupervised Learning: Basics
Private Python learning procedure
Learning Python with ChemTHEATER 02
Learning Python with ChemTHEATER 01
Note to daemonize python
Note: python Skeleton Nya
Python basic grammar note (4)
Python basic grammar note (3)
Python: Deep Learning Tuning
Python + Unity Reinforcement Learning (Learning)
Python: Supervised Learning (Regression)
Python Tkinter Primer Note
Python: Supervised Learning (Classification)
[Note] Python, when starting machine learning / deep learning [Links]
Effective Python Learning Memorandum Day 15 [15/100]
Note
Python exception handling (Python learning memo ⑥)
Mayungo's Python Learning Note: List of stories and links
O'Reilly python3 Primer Learning Notes
Learning flow for Python beginners
Python
Effective Python Learning Memorandum Day 6 [6/100]
Effective Python Learning Memorandum Day 12 [12/100]
Python: Supervised Learning: Hyperparameters Part 1
Python learning plan for AI learning
Effective Python Learning Memorandum Day 9 [9/100]
Effective Python Learning Memorandum Day 8 [8/100]
Reinforcement learning starting with Python
Machine learning with Python! Preparation
Python Input Note in AtCoder
[Note] Operate MongoDB with Python