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()