I have written an answer to this question on Stack Overflow. To make it easier for you, I have copy-pasted the question below.
Your friend wants to try to make a word ladder! This is a list of words where each word has a one-letter difference from the word before it.
Here’s an example:
cat cot cog log
Write a program to help your friend. It should do the following:
Ask your friend for an initial word.
Repeatedly ask them for an index and a letter.
You should replace the letter at the index they provided with the letter they enter.
You should then print out the new word.
Stop asking for input when the user enters -1 for the index.
My answer to this is:
import os
get_index = 0
word = input("Enter a word: ")
for i in range(len(word)):
while True:
try:
get_index = int(input("Enter an index (-1 to quit): "))
if get_index == -1:
os._exit(0)
elif get_index < -1 or get_index > 2:
raise ValueError
except ValueError:
print ("Invalid index!")
else:
while True:
try:
letter = input("Enter a letter: ")
for c in letter:
if c.isupper():
raise ValueError
except ValueError:
print ("Character must be a lowercase letter!")
else:
if len(letter) > 1:
print ("Must be exactly one character!")
else:
word = word[:get_index] + letter + word[get_index + 1:]
print (word)
break
NOTE #1: Here is a link to the program run (output): OUTPUT
NOTE #2: I would also like to use an alternative for os._exit()
as it takes time for the program to completely end.
So, I would like to know whether I could make this code shorter and more efficient.
Any help would be highly appreciated.