Question

Writing in Python. Need help making this program: Hanoi's tower is an old game that can...

Writing in Python. Need help making this program:

Hanoi's tower is an old game that can be solved with a recursive algorithm. Wikipedia contains example implementations of this.
You will write a variant of this implementation that prints the condition of the three stacks of slices after each move. Remember that the different recursive calls will refer to different stacks, so in order to print a status that is comparable between calls, the method that prints the stacks must have its own references to the stacks. One way to do this is to define a class Hanoi, let the three stacks of slices be instance variables, let the print method be an instance method, and let the recursive method itself be an instance method as well.
The driving time to Towers of Hanoi is O (2n) where n is the number of slices in the stack. Analyze their algorithm to find out why.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

SOURCE CODE:

*Please follow the comments to better understand the code.

**Please look at the Screenshot below and use this code to copy-paste.

***The code in the below screenshot is neatly indented for better understanding.


# Let us say we want to perform the TowersOfHanoi with 3 disks
NUM_OF_DISKS = 3

class Tower:
"""Create the tower class here ."""

def __init__(self, name, n_disks = 0):
self.name = name
self.disks = []

for i in range(n_disks, 0, -1):
self.push(str(i))

# Push the disk to the tower
def push(self, disk):
self.disks.append(disk)

# Pop the disk to tower
def pop(self):
return self.disks.pop()

# Print the tower here
def __str__(self):
disks = ''.join('{:<2}'.format(d) for d in self.disks)
return '{}: {}'.format(self.name, disks)


class TowersOfHanoi:
"""Represents the Tower of Hanoi's problem and solution."""

def __init__(self, n_disk):
self.n_disk = n_disk
self.n_move = 0
self.prepare_towers()

# Prepare the 3 towers here
def prepare_towers(self):
s = Tower('src', self.n_disk)
d = Tower('dest')
e = Tower('temp')

self.towers = [s, d, e]

# Start the solution here
def start(self):
self.print_the_current_towers()
s, d, e = self.towers
self.move_the_disk(s, d, e, self.n_disk)

# Move the disks here
def move_the_disk(self, s, d, e, n):
if n <= 0:
return

self.move_the_disk(s, e, d, n - 1)

self.n_move += 1
print('move disk-{} from {} to {} ({}).'.format(str(n), s.name, d.name, self.n_move))
disk = s.pop()
d.push(disk)
self.print_the_current_towers()

self.move_the_disk(e, d, s, n - 1)

# Print the current towers here
def print_the_current_towers(self):
for t in self.towers:
print(t)

# START the program here
print('TOH is started.')

towers_of_hanoi = TowersOfHanoi(NUM_OF_DISKS)
towers_of_hanoi.start()

# END HERE
print('TOH is finished.')

======================================

SCREENSHOT:

OUTPUT:

TOH is started.
src: 3 2 1
dest:
temp:
move disk-1 from src to dest (1).
src: 3 2
dest: 1
temp:
move disk-2 from src to temp (2).
src: 3
dest: 1
temp: 2
move disk-1 from dest to temp (3).
src: 3
dest:
temp: 2 1
move disk-3 from src to dest (4).
src:
dest: 3
temp: 2 1
move disk-1 from temp to src (5).
src: 1
dest: 3
temp: 2
move disk-2 from temp to dest (6).
src: 1
dest: 3 2
temp:
move disk-1 from src to dest (7).
src:
dest: 3 2 1
temp:
TOH is finished.


Add a comment
Know the answer?
Add Answer to:
Writing in Python. Need help making this program: Hanoi's tower is an old game that can...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • program in python Randomness can be used to improve the performance of deterministic algorithms which need...

    program in python Randomness can be used to improve the performance of deterministic algorithms which need to make many choices. Rather than repeatedly making fixed, hard-coded choices, a pseudorandom number generator can be used to make dynamic, unbiased choices. If the benefits of "good" choices outweigh the costs of "bad" choices, a random selection of good and bad choices can improve the performance of an algorithm Let us explore this with the QUICKSELECT algorithm. Discovered by the influential computer science...

  • C++ PROGRAM ONLY! For this lab you need to write a program that will read in...

    C++ PROGRAM ONLY! For this lab you need to write a program that will read in two values from a user and output the greatest common divisor (using a recursive implementation of the Euclidean algorithm) to a file. In Lab #3, you implemented this program using an iterative method. Greatest Common Divisor In mathematics, the greatest common divisor (GCD) of two or more integers (when at least one of of them is zero then the larger value is the GCD....

  • Program Purpose In this program you will demonstrate your knowledge in programming OOP concepts, such as classes, encapsulation, and procedural programming concepts such as lınked lists, dynamic me...

    Program Purpose In this program you will demonstrate your knowledge in programming OOP concepts, such as classes, encapsulation, and procedural programming concepts such as lınked lists, dynamic memory allocation, pointers, recursion, and debugging Mandatory Instructions Develop a C++ object oriented solution to the Towers of Hanoi puzzle. Your solution will involve designing two classes one to represent individual Disk and another to represent the TowersOfHanoi game. TowersOfHanoi class will implement the game with three linked lists representing disks on each...

  • JAVA 3 LECTURE REVIEW PLEASE NEED ANSWERS ASAP. DUE IN AN HOUR!!! Question 12 points The...

    JAVA 3 LECTURE REVIEW PLEASE NEED ANSWERS ASAP. DUE IN AN HOUR!!! Question 12 points The best-case performance for a shell sort is: --- O(1) O(n2)   O(n) O(n log n)   Signaler cette question Question 22 points The best-case performance for an array of n items using insertion sort is: --- O(n2)   O(n) O(1) there is no best-case Signaler cette question Question 3 2 points A recursive method that processes a chain of linked nodes --- uses the first node in...

  • I need help writing this code in C++ Proj11.cpp is provided as well as the randomdata.txt thank you in advance! Objectives: The main objectives of this project is to introduce you to recursion,...

    I need help writing this code in C++ Proj11.cpp is provided as well as the randomdata.txt thank you in advance! Objectives: The main objectives of this project is to introduce you to recursion, and test your ability to work with some STL functionalities. A review of your knowledge on working with templates, dynamic data structures, as well as manipulating dynamic memory, classes, pointers and iostream to all extents, is also included. Description: For the entirety of this project, you will...

  • JAVA 3 PLEASE ANSWER AS MANY QUESTIONS AS POSSIBLE! ONLY 2 QUESTIONS LEFT THIS MONTH!!! Question...

    JAVA 3 PLEASE ANSWER AS MANY QUESTIONS AS POSSIBLE! ONLY 2 QUESTIONS LEFT THIS MONTH!!! Question 12 pts Which is a valid constructor for Thread? Thread ( Runnable r, int priority ); Thread ( Runnable r, String name ); Thread ( int priority ); Thread ( Runnable r, ThreadGroup g ); Flag this Question Question 22 pts What method in the Thread class is responsible for pausing a thread for a specific amount of milliseconds? pause(). sleep(). hang(). kill(). Flag...

  • You need not run Python programs on a computer in solving the following problems. Place your...

    You need not run Python programs on a computer in solving the following problems. Place your answers into separate "text" files using the names indicated on each problem. Please create your text files using the same text editor that you use for your .py files. Answer submitted in another file format such as .doc, .pages, .rtf, or.pdf will lose least one point per problem! [1] 3 points Use file math.txt What is the precise output from the following code? bar...

  • What is the role of polymorphism? Question options: Polymorphism allows a programmer to manipulate objects that...

    What is the role of polymorphism? Question options: Polymorphism allows a programmer to manipulate objects that share a set of tasks, even though the tasks are executed in different ways. Polymorphism allows a programmer to use a subclass object in place of a superclass object. Polymorphism allows a subclass to override a superclass method by providing a completely new implementation. Polymorphism allows a subclass to extend a superclass method by performing the superclass task plus some additional work. Assume that...

  • could you please help me with this problem, also I need a little text so I...

    could you please help me with this problem, also I need a little text so I can understand how you solved the problem? import java.io.File; import java.util.Scanner; /** * This program lists the files in a directory specified by * the user. The user is asked to type in a directory name. * If the name entered by the user is not a directory, a * message is printed and the program ends. */ public class DirectoryList { public static...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT