Jack F
Jack F

Reputation: 553

solving Tower of Hanoi recursively

I know the idea behind the Tower of Hanoi and know the algorithm but I am having trouble implementing it.

class Hanoi:
    def __init__(self, n):
       == code==

    def move(self, src, dst):
   =code for moving the disk from source to destination==

    def spare(self, src, dst):
    ==Returns the peg which is not src and dst==

    def print_pegs(self):


h = Hanoi(4)

def hanoi(n, src, dst):         
        if n==1:
           h.move(src,dst)
        else:
            spare=h.spare(src,dst)
            hanoi(n-1,src,spare)
            hanoi(1,src,dst)
            hanoi(n-1,spare,dst)

hanoi(4, 0, 2)

The problem I am having is I don't know how to combine the recursive definition with the class function to move the disks.

Upvotes: 1

Views: 1840

Answers (1)

YXD
YXD

Reputation: 32521

You need to put the recursive calls inside the body of move() and spare() and move the logic of your function hanoi() into the relevant methods

so

class Hanoi(object):

    # snip

    def move(self, src, dst):

        # your logic goes here
        # example of a recursive call
        self.move(foo, bar)

Upvotes: 1

Related Questions