I’m working on solving the Tower of Hanoi problem and need to count the total number of moves required for n disks. Currently, I’ve implemented a solution where the move count is tracked using a global variable, but I’d like to refactor this code to eliminate the use of global variables without altering the function signature.
Here’s the code I currently have:
count = 0
def hanoi(n, a, b, c):
global count
if n == 1:
count += 1
else:
hanoi(n - 1, a, c, b)
hanoi(1, a, b, c)
hanoi(n - 1, b, a, c)
hanoi(10, "A", "B", "C")
print(count)
How can I track the number of moves made during the recursion and return the total count without using global variables or modifying the function signature?
kavindya ranasinghe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
Dont ‘track’ it, just return it:
def hanoi(n, a, b, c):
if n == 1:
return 1
return hanoi(n - 1, a, c, b) +
hanoi(1, a, b, c) +
hanoi(n - 1, b, a, c)
print(hanoi(10, "A", "B", "C"))