Towers of Hanoi Graphic (well, "ASCII - Graphic") Output


This post references the “Linear Data Structures” project. Here is a function that will present each round as a series of underscores formatted to resemble the disks:

____          _                   
_____         __                  
L             M           R

To use it, you need access to the status of each stack at any given time. The function, print_items() in the module provides this information, but outputs it in a printed format that is not too useful. There are a couple of ways to get at the underlying information. I chose to simply change the output of that function from print() to return. So

  1. In that function, comment out the last two lines:
        print("{0} Stack: {1}".format(self.get_name(), print_list))
  1. … and add the line
    return print_list

  2. Now, in the module, under the heading # Play the Game, comment out the lines

    for stack in stacks:
  1. … and replace them with:

  2. Finally, copy the entire function below, and paste it into your module somewhere above #Play the Game

def print_pix():
    # render current state as a list of lists of values
    show_list = []
    for stack in stacks:        
    # pad lists with leading zeros so all are length = num_dusks
    for idx, item in enumerate(show_list):
        new_list = [0 for i in range(num_disks - len(item))]
        show_list[idx] = new_list + show_list[idx]    
    # print num_disks lines, each comprised of
    # ... three columns, correspunding to "L", "M", and "R".
    # ... Each column will consist of a number of underscores
    # ... corresponding to the value of the node at that level.
    for i in range(num_disks):
        for item in show_list:           
            mult = item[i]
            s = "_" * mult
            print("{:10}".format(s), end = '')

I hope you enjoy it!

P.S. : Tired of trying to solve that 7-ring tower? Try this!

Towers of Hanoi - Watch it unfold through recursion!