Skip to content

Instantly share code, notes, and snippets.

@rajatdiptabiswas
Last active February 14, 2018 08:59
Show Gist options
  • Save rajatdiptabiswas/6fda5e2be982f24c5587928e1ff10345 to your computer and use it in GitHub Desktop.
Save rajatdiptabiswas/6fda5e2be982f24c5587928e1ff10345 to your computer and use it in GitHub Desktop.
Python program to solve the Tower of Hanoi problem recursively
#!/usr/bin/env python3
def tower_of_hanoi(number, beginning, auxiliary, ending):
if number == 1:
print("{} -> {}".format(beginning, ending))
return
else:
tower_of_hanoi(number-1, beginning, ending, auxiliary)
tower_of_hanoi(1, beginning, auxiliary, ending)
tower_of_hanoi(number-1, auxiliary, beginning, ending)
def main():
n = int(input("Enter the number of pieces: "))
beg = input("Enter the starting rod: ")
aux = input("Enter the auxiliary rod: ")
end = input("Enter the final rod: ")
tower_of_hanoi(n, beg, aux, end)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment