Python Forum
Towers of Hanoi - print 3 Towers
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Towers of Hanoi - print 3 Towers
#1
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.
Reply
#2
(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
Reply
#3
@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('+++++++      +++++++++     +++++++       ')
Reply
#4
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()
Gribouillis likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Puzzle Tower of Hanoi anickone 1 2,129 Nov-19-2019, 02:09 AM
Last Post: SheeppOSU

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020