Chapter 3 Stacks and Queues - 3.4

Problem 3.4: In the classic problem of the Towers of Hanoi, you have 3 rods and N disks fo different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (e.g., each disk sits on top of an even larger one). You have the following constrains:
(A) Only one disk can be moved at a time.
(B) A disk is slid off the top of one rod onto the next rod.
(C) A disk can only be placed on top of a larger disk.
Write a program to move the disks from the first rod to the last using Stacks.


So classic, so recursive:P
from stack import *
rods = [stack(), stack(), stack()]
def Hanoi(n, rod_from, rod_to):
    if n == 2:
        Move(rod_from, 3 - (rod_from + rod_to))
        Move(rod_from, rod_to)
        Move(3 - (rod_from + rod_to), rod_to)
    else:
        Hanoi(n - 1, rod_from, 3 - (rod_from + rod_to))
        Move(rod_from, rod_to)
        Hanoi(n - 1, 3 - (rod_from + rod_to), rod_to)
def Move(rod_from, rod_to):
    print "Move from", rod_from, "to", rod_to
    rods[rod_to].push(rods[rod_from].pop())

# Test case
if __name__ == "__main__":
    # range(1, 8)[::-1] gets a reverse list
    # Sequence slicing [starting-at-index : but-less-than-index [ : step]].
    # Start defaults to 0, end to len(sequence), step to 1
    for i in range(1, 8)[::-1]:
        rods[0].push(i)
    Hanoi(7, 0, 2)
    for i in range(0, 7):
        print "rods[2].pop():", rods[2].pop()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章