Created
April 23, 2019 00:50
-
-
Save shiracamus/d1d308a74417a3024beb2e974034f4a8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
class Hanoi: | |
def __init__(self, n): | |
self.n = n | |
self.tower = list(range(1, n+1))[::-1], [], [] | |
def solve(self): | |
yield from self.move(self.n, 0, 1, 2) | |
def move(self, n, x, y, z): | |
if(n == 0): | |
return | |
# n-1を経由地へ移動(再帰呼び出し) | |
yield from self.move(n-1, x, z, y) | |
# 移動 | |
self.tower[z].append(self.tower[x].pop()) | |
# 出力 | |
yield x, z | |
# n-1を経由地から移動先へ(再帰呼び出し) | |
yield from self.move(n-1, y, x, z) | |
def print(self): | |
print("a:", *self.tower[0]) | |
print("b:", *self.tower[1]) | |
print("c:", *self.tower[2]) | |
def main(): | |
n = int(input("hanoiの数: ")) | |
print("予想手数:", "2^n -1 -> ", 2**n - 1) | |
s = int(input("スリープ(秒): ")) | |
hanoi = Hanoi(n) | |
hanoi.print() | |
for count, (f, t) in enumerate(hanoi.solve(), 1): | |
print("----------------------------------------------") | |
print(count, "手目: ", "abc"[f], "->", "abc"[t]) | |
hanoi.print() | |
time.sleep(s) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment