PutsandCalls
PutsandCalls

Reputation: 1011

Tower of Hanoi Representation

I'm having trouble implementing the problem in python as follows. I understand the original Tower of Hanoi problem which is that one can move $N$ disks to say the 3rd disk, and there are algorithms to do so but I am unable to figure out how to list out each of the individual disks at each stage. The problem is as follows:

enter image description here

I figured that I could use a binomial tree representation shown as follows:

enter image description here

So far the rough skeleton code I thought of would look something along the lines of

def recursion(m,n,T):
    pos = list(range(1,m))
    index = 0
    values = list(range(1,n))
    tree = []
    if pos[index+1] > pos[index]:
        pos[index + 1] -=  pos[index+1]
        pos[index + 2] += pos[index+1]
        tree.append(pos)
    if pos[index+1] < pos[index]:
        pos[index+1] += pos[index]
        pos[index] -= pos[index]
        tree.append(pos)
    else:
        recursion()
    return tree

I would greatly appreciate some help with this

Upvotes: 0

Views: 885

Answers (2)

grepit
grepit

Reputation: 22392

This is very similar to ksai solution except this is for python 3 and I removed the extra print and return statement

def move(disk , from_rod, to_rod, aux_rod):
    if disk >= 1:
        move(disk-1, from_rod, aux_rod, to_rod)
        print ("Move disk", disk, "from rod", from_rod, "to rod", to_rod)
        move(disk-1, aux_rod, to_rod, from_rod)

n = 3
move(n, 'A', 'B', 'C')

output:

enter image description here

Upvotes: 0

ksai
ksai

Reputation: 977

You didn't pass no. of disks to your function, and this number must be decreased at every next call you make to the function. And there is a condition to break further recursion. Here is the modified form

# n = no. of rods
def recurse(n , from_rod, to_rod, aux_rod):
    if n == 1:
        print "Move disk 1 from rod", from_rod, "to rod",to_rod
        return
    recurse(n-1, from_rod, aux_rod, to_rod)
    print "Move disk", n, "from rod", from, "to rod", to
    recurse(n-1, aux_rod, to_rod, from_rod)

n = 5
recurse(n, 'A', 'B', 'C')

Upvotes: 1

Related Questions