LINEAR DATA STRUCTURES Towers of Hanoi

if you have the time, can you please look at my code and see why it keeps printing the second print statement, whichever way i play the game it keeps looping back to that print out

      num_user_moves += 1
      break  
    else:
      print("\n\nInvalid Move. Try Again")

from the code below, when i try to play the game:

from stack import Stack

print("\nLet's play Towers of Hanoi!!")

#Create the Stacks
stacks = []

left_stack = Stack("left")
middle_stack = Stack("middle")
right_stack = Stack("right")

stacks.append(left_stack)
stacks.append(middle_stack)
stacks.append(right_stack)
#Set up the Game
num_disks = int(input("\nHow many disks do you want to play with?\n"))
while num_disks < 3:
  num_disks = int(input("Enter a number greater than or equal to 3\n"))

for disk in range(num_disks, 0, -1):
  left_stack.push(disk)
#left_stack.print_items()
num_optimal_moves = 2**num_disks - 2
print("\nThe fastest you can solve this game is in {0} moves".format(num_optimal_moves))


def get_input():
  choices = [s.get_name()[0] for s in stacks]
  while True:
    
    for i in range(len(stacks)):
      name = stacks[i].get_name()
      letter = choices[i]
      print("Enter {0} for {1}".format(letter, name))
    user_input = input("")  
    if user_input in choices:
      for i in range(len(stacks)):
        return stacks[i]

      

num_user_moves = 0

while right_stack.get_size() != num_disks:
  print("\n\n\n...Current Stacks...")
  
  for stack in stacks:
    stack.print_items()

  while True:
    print("\nWhich stack do you want to move from?\n")  
    from_stack = get_input()
    print("\nWhich stack do you want to move to?\n")
    to_stack = get_input()
    if from_stack.get_size() == 0:
      print("\n\nInvalid Move. Try Again")
    elif to_stack.get_size() == 0 or from_stack.peek() < to_stack.peek():
      disk = from_stack.pop()
      to_stack.push(disk)
      num_user_moves += 1
      break  
    else:
      print("\n\nInvalid Move. Try Again")  

print("\n\nYou completed the game in {0} moves, and the optimal number of moves is {1}".format(num_user_moves, num_optimal_moves))    


exercise link:
https://www.codecademy.com/paths/computer-science/tracks/linear-data-structures/modules/cspath-stacks/projects/towers-of-hanoi

1 Like

Hi,

You need to set up some tracer print statements in your while loop that help you track the variable. It helps if you format the string to say "x_variable is this: ". This should bring you closer to why the loop isn’t behaving as you want it to.

1 Like

i tried doing that, its weird my code looks identical to the solution now but still the loop doesnt work :confused:

Are you running the same python version? The codecademy console defaults to 2. I did this exercise in 3 so i had to run it by python3 script.py

1 Like

Have you checked carefully what values are being fed to the logic statements? If a particular flow is observed the previous statements must not be evaluating to True at any point. You’d need to find out why and if a guess doesn’t help just print it out.

2 Likes

i dont get it it is supposed to repeat this last while loop until it is false right? but it only does it once

while right_stack.get_size() != num_disks:
  print("\n\n\n...Current Stacks...")
  
  for stack in stacks:
    stack.print_items()

  while True:
    print("\nWhich stack do you want to move from?\n")  
    from_stack = get_input()
    print("\nWhich stack do you want to move to?\n")
    to_stack = get_input()
    if from_stack.get_size() == 0:
      print("\n\nInvalid Move. Try Again")
    elif to_stack.get_size() == 0 or from_stack.peek() < to_stack.peek():
      disk = from_stack.pop()
      to_stack.push(disk)
      num_user_moves += 1
      break  
    else:
      print("\n\nInvalid Move. Try Again")  

Since your while loop condition is just the boolean True that would be an infinite loop unless it was deliberately broken. If it’s not running indefinitely then there must be something which causes the loop to end. If you follow the flow of your program you could potentially work out which statements were being executed for this behaviour to be observed.

If that’s not what you expected your program to do then you’ll need to work out why. If you can’t spot an error from just reading code then both @toastedpitabread and myself have suggested a valid next step. Have you tried that yet?

yes i went through it 4 times today with the solution, i even checked all the program that was given to me (not written by me)
i dont think its an issue of different python versions.

maybe im missing something…
anyhow thank you for your help, sorry dont wanna take much of your time with this

Don’t let it get you down! You can always keep going in the lessons and after a while come back and check to see if you can fix this one. I went through the whole Codecademy CS path like this. It’s better not to get stuck too heavily on any one idea.

yes i will move on! thanks for the advice. i mean i understand the whole concept but i donno whats going on. thank you

Do try and work this one out at some point. Debugging is an important skill that you’ll almost inevitably wind up having to use. Even if it’s not your own code that’s going wrong it can help you wrap your head around what someone else has written.

yes! very true. will definitely do that