 # Tower Of Hanoi Problem. Invalid Move

i’ve made it right to the end of this projects but whenever I try to make a move i always get a “invalid move” response. Can’t work this one out at all. Any ideas? thanks ``````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 += [left_stack, middle_stack, 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)

num_optimal_moves = (2**num_disks) -1
print("\nThe fastest you can solve this game is in {} moves".format(str(num_optimal_moves)))

#Get User Input
def get_input():
choices = [stack.get_name() for stack 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]

#Play the Game

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

``````
3 Likes

There is a problem in your `get_input` function. It contains this statement within a `for` loop:

``````        return stacks[i]
``````

That statement should execute only when `user_input` is equivalent to `choices[i]`. Use an `if` statement to ensure that the `return` statement executes only under that circumstance. Otherwise, it will always execute during the first iteration of the loop.

2 Likes

Thank you! I added a line and it worked! This is a part i struggled on so i used the walkthrough video to go over this and uses the same code as there so i couldn’t work out why it wouldn’t work?

3 Likes

Unfortunately, the walkthrough video omits that `if` header, as indicated by the screen capture below (made February 20, 2019). Without that test, the function can only `return` the `Stack` at index `0` within `stacks`, which is `left_stack`, and the user cannot complete a valid move.

3 Likes

ok got it! thanks

3 Likes