Search code examples
pythonpython-3.xalgorithmcountglobal-variables

Count the moves of hanoi tower


I am trying to count the moves of hanoi tower

In [4]: %paste      
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")
## -- End pasted text --

In [5]: print(count)
1023

The above solution employed the global keyword,
How could get it done if not introducing global?


Solution

  • With a bit of refactoring to make the function recursive with a common count variable:

    def hanoi(n, a, b, c):
        count = 0
        if n == 1:
            count += 1
        else:
            count += hanoi(n - 1, a, c, b)
            count += hanoi(1, a, b, c)
            count += hanoi(n - 1, b, a, c)
        return count
    

    Output

    >>> hanoi(10, "A", "B", "C")
    1023