Introduction to Programming using Python 1st Edition

Published by Pearson
ISBN 10: 0132747189
ISBN 13: 978-0-13274-718-9

Chapter 15 - Recursion - Programming Exercises - Page 525: 15.18

Answer

code

Work Step by Step

# 15.18 (Towers of Hanoi) Modify Listing 15.8, TowersOfHanoi.py, so that the program # finds the number of moves needed to move n disks from tower A to tower B. # (Hint: Use a global variable and increment it for every move.) steps = 0 def main(): n = eval(input("Enter number of disks: ")) # Find the solution recursively print("The moves are:") moveDisks(n, 'A', 'B', 'C') print("The number of steps is: ", steps) # The function for finding the solution to move n disks # from fromTower to toTower with auxTower def moveDisks(n, fromTower, toTower, auxTower): global steps if n == 1: # Stopping condition print("Move disk", n, "from", fromTower, "to", toTower) steps += 1 else: moveDisks(n - 1, fromTower, auxTower, toTower) print("Move disk", n, "from", fromTower, "to", toTower) steps += 1 moveDisks(n - 1, auxTower, toTower, fromTower) main() # Call the main function
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.