Predict the output
What does this print?
word = "cat"
allowed = {"cot", "cut", "bat", "dog"}
next_words = sorted(word[:i] + ch + word[i + 1:]
for i in range(len(word))
for ch in "abcdefghijklmnopqrstuvwxyz"
if word[:i] + ch + word[i + 1:] in allowed)
print(next_words)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A ['bat', 'cot', 'cut']
Right: each differs from 'cat' in exactly one letter.
Trying each position with each letter finds one-letter neighbours without comparing every pair of words.
Why not the others?
- B ['bat', 'cot', 'cut', 'dog']. 'dog' differs in all three letters.
- C ['cot', 'cut']. Changing the first letter gives 'bat', which is allowed.