Professional Documents
Culture Documents
Ex 4
Ex 4
Algorithm:
1. Stack Class:
• Initialize an empty list in the __init__ method to store stack items.
• Implement methods:
• is_empty: Returns True if the stack is empty, False otherwise.
• push(item): Appends an item to the stack.
• pop: Removes and returns the last item added to the stack (if not
empty).
• peek: Returns the last item added to the stack without removing it (if
not empty).
• size: Returns the number of items in the stack.
2. Towers of Hanoi Function (towers_of_hanoi):
• Initialize three stacks (source_stack, auxiliary_stack, and target_stack) to
represent the three pegs in the Towers of Hanoi.
• Fill the source_stack with n disks initially.
• Define a helper function move_disk(start, end, start_stack, end_stack) to
move a disk from one peg to another.
• Define a recursive function hanoi_recursive(n, source, auxiliary, target,
source_stack, auxiliary_stack, target_stack):
• Base Case: If n is 0, return.
• Recursive Steps:
1. Move n-1 disks from the source peg to the auxiliary peg using
the target peg as the auxiliary peg.
2. Move the nth disk from the source peg to the target peg.
3. Move the n-1 disks from the auxiliary peg to the target peg
using the source peg as the auxiliary peg.
3. Example Usage:
• Call hanoi_recursive with n disks, source peg 'A', auxiliary peg 'B', and target
peg 'C'.
• The movement of each disk is printed during the process.
Program:
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def pop(self):
if not self.is_empty():
return self.items.pop()
def peek(self):
if not self.is_empty():
return self.items[-1]
def size(self):
return len(self.items)
# Move the n-1 disks from auxiliary to target using source as the auxiliary rod
hanoi_recursive(n-1, auxiliary, source, target, auxiliary_stack, source_stack,
target_stack)
# Example usage:
towers_of_hanoi(3, 'A', 'B', 'C')
Output:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
>