Skip to content

Commit b55da6c

Browse files
committed
Added parameter to display all the steps while solving the puzzle in tower_of_hanoi_stack.py
1 parent 68d05f2 commit b55da6c

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

tower_of_hanoi_stack.py

+21-7
Original file line numberDiff line numberDiff line change
@@ -29,25 +29,39 @@ def add_disks(self, no_of_disks: int) -> None:
2929
else:
3030
raise self.__AlreadySolvedError
3131

32-
def display(self) -> None:
32+
def display(self, show_title: bool = True) -> None:
33+
if show_title:
34+
print("Source - Auxiliary - Destination")
3335
print(self.__source_rod, end=' - ')
3436
print(self.__auxiliary_rod, end=' - ')
3537
print(self.__destination_rod)
3638

37-
def __tower_of_hanoi(self, disks: int, source: Stack, destination: Stack, auxiliary: Stack) -> None:
39+
def __tower_of_hanoi(self, disks: int, source: Stack, destination: Stack, auxiliary: Stack,
40+
display_steps: bool) -> None:
41+
if disks == self.__no_of_disks and display_steps:
42+
print("Source - Auxiliary - Destination")
3843
if disks == 1:
3944
source.pop()
4045
destination.push('disk 1')
46+
if display_steps:
47+
self.display(False)
4148
elif disks > 1:
42-
self.__tower_of_hanoi(disks - 1, source=source, destination=auxiliary, auxiliary=destination)
49+
self.__tower_of_hanoi(disks - 1, source=source, destination=auxiliary, auxiliary=destination,
50+
display_steps=display_steps)
4351
source.pop()
4452
destination.push(f'disk {disks}')
45-
self.__tower_of_hanoi(disks - 1, source=auxiliary, destination=destination, auxiliary=source)
53+
if display_steps:
54+
self.display(False)
55+
self.__tower_of_hanoi(disks - 1, source=auxiliary, destination=destination, auxiliary=source,
56+
display_steps=display_steps)
4657

47-
def start(self) -> None:
58+
def solve(self, display_steps: bool = False) -> None:
4859
if self.__no_of_disks < 1:
4960
raise self.__EmptySourceRodError
50-
self.__tower_of_hanoi(len(self.__source_rod), self.__source_rod, self.__destination_rod, self.__auxiliary_rod)
61+
if display_steps:
62+
print("Steps:")
63+
self.__tower_of_hanoi(len(self.__source_rod), self.__source_rod, self.__destination_rod, self.__auxiliary_rod,
64+
display_steps)
5165
self.__solved = True
5266

5367
def reset(self) -> None:
@@ -65,7 +79,7 @@ def reset(self) -> None:
6579
tower.add_disks(2)
6680
print("Unsolved")
6781
tower.display()
68-
tower.start()
82+
tower.solve(display_steps=True)
6983
print("Solved")
7084
tower.display()
7185
tower.reset()

0 commit comments

Comments
 (0)