I’ve got up to Step 28 of Towers of Hanoi, and my get_input() function has suddenly started glitching. Whenever I try to run my code, it throws the following error:
I checked the offending line of code, but it matches what the project’s video recommends perfectly near as I can tell. Just in case I’m wrong, here it is:
choices = [stack.get_name()[0] for stack in stacks]
I hope someone can help me with this!
Never mind! I found my problem.
I have enabled small case letter as well as large case letter to accept as input
from stack import Stack
print("\nLet's play Towers of Hanoi!!")
#Create the Stacks
stacks = []
left_stack = Stack('Left')
right_stack = Stack('Right')
middle_stack = Stack('Middle')
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) - 1
print('\nThe fastest you can solve this game is in {} moves'.format(num_optimal_moves))
#Get User Input
def get_input():
choices = [str(stack.get_name()[0]) for stack in stacks]
choices_lower = [str(stack.get_name()[0].lower()) for stack in stacks]
while True:
for i in range(len(stacks)):
name = stacks[i].get_name()
#print(type(name))
letter = choices[i]
print("Enter {letter} for {name}".format(letter=letter, name=name))
user_input = str(input())
if user_input in choices or user_input.lower() in choices_lower:
#print(type(user_input))
for i in range(len(stacks)):
if user_input.lower() == stacks[i].get_name()[0].lower():
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()
if from_stack.is_empty():
print('\n\nInvalid Move. Try Again')
print('\nWhich stack do you wan to move to?\n')
to_stack = get_input()
if to_stack.is_empty() or to_stack.peek() > from_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))