If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Certainly! Here's an example implementation of the Tower of Hanoi problem using recursion in Python:
pythonCopy code
def tower_of_hanoi(n, source, destination, auxiliary):
if n == 1:
print(f"Move disk from {source} to {destination}")
else:
tower_of_hanoi(n - 1, source, auxiliary, destination)
print(f"Move disk from {source} to {destination}")
tower_of_hanoi(n - 1, auxiliary, destination, source)
Let's break down how the code works:
tower_of_hanoi function takes four parameters: n (the number of disks), source (the source peg), destination (the destination peg), and auxiliary (the auxiliary peg).n == 1). In this case, we directly move the disk from the source peg to the destination peg.n-1 disks from the source peg to the auxiliary peg using the destination peg as the temporary peg, using a recursive call to tower_of_hanoi.n-1 disks, we move the remaining disk (disk n) from the source peg to the destination peg.n-1 disks from the auxiliary peg to the destination peg using the source peg as the temporary peg.Here's an example usage of the tower_of_hanoi function:
pythonCopy code
tower_of_hanoi(3, 'A', 'C', 'B')
In this example, we solve the Tower of Hanoi problem with 3 disks, starting from peg 'A', moving them to peg 'C', using peg 'B' as the temporary peg. The function will print the sequence of moves to solve the problem:
cssCopy code
Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C
The output shows the sequence of moves required to solve the Tower of Hanoi puzzle with 3 disks.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support