Python Forum

Full Version: Towers of Hanoi - print 3 Towers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I'm developing Towers of Hanoi as a console application.
It doesn't matter whether the 3 towers are stored in 3 stacks or 3 arrays.
I'm looking for an algorithm with which I can print 3 towers side by sideĀ 
with the Python Print command.
(Oct-12-2020, 08:42 PM)PythonMarlem Wrote: [ -> ]Hello,

I'm developing Towers of Hanoi as a console application.
It doesn't matter whether the 3 towers are stored in 3 stacks or 3 arrays.
I'm looking for an algorithm with which I can print 3 towers side by sideĀ 
with the Python Print command.

recursive algorithm would be better to solve tower of hanoi
@sanrock123 There is basically a single way to solve the three towers problems. Here the OP only wants to print the towers. I suggest combining lines such as
print('+++++++      +++++++++     +++++++       ')
I make strings for each disk. The strings are all the same width so they can be concatenated in any order and maintain alignment.
# Can specify any number of disks > 0
num_disks = 5

# There are three posts.  Initially all disks are on the left post
posts = [list(range(1, num_disks+1)), [], []]

# Make strings used to draw disks.  Disk 0 is an empty post '#', other
# disks are strings of letters.  Each disk is wider than the previous.
disk_pics = []
symbols = '#ABCDEFGHJKLMNOPQRSTUVWXYZ'
for i in range(num_disks + 1):
    spaces = ' '*(num_disks-i)
    disk_pics.append(spaces + symbols[i]*(i*2+1) + spaces)

# Make post labels
spaces = ' '*num_disks
post_labels = spaces + '1 ' + spaces*2 + ' 2 ' + spaces*2 + ' 3 '

# Get disk string for specified level
def disk_pic(level, post):
    index = max(0, level + len(posts[post]) - num_disks)
    return disk_pics[index]

# Print out the posts and disks
def print_posts():
    for level in range(num_disks+1):
        print('  '.join([disk_pic(level, i) for i in range(len(posts))]))
    print(post_labels)

print('\n\nThe Towers of Hanoi')
print_posts()