Challenge: Climb the word ladder
Kuda's teacher puts a puzzle on the board every Friday: turn cold into warm, changing one letter at a time, and every step must be a real word.
cold
cord (l became r)
card (o became a)
ward (c became w)
warm (d became m)
The class hands in their answers on paper and the teacher has 40 to mark. Let's help with the checking part.
Your task
Write two functions:
one_letter_apart(a, b)returnsTrueif the two words have the same length and differ in exactly one position, otherwiseFalse.is_ladder(words)returnsTrueif every word in the list is one letter apart from the word before it.
one_letter_apart("cold", "cord") # True
one_letter_apart("cold", "warm") # False (4 letters differ)
one_letter_apart("cat", "cat") # False (nothing changed)
one_letter_apart("cat", "cart") # False (different lengths)
is_ladder(["cold", "cord", "card", "ward", "warm"]) # True
is_ladder(["cold", "cord", "warm"]) # False
is_ladder(["kombi"]) # True
is_ladder([]) # False
Rules
- Words are in lowercase.
- Swapping letters around does not count:
dogandgoddiffer in two places. - You do not need to check that the words are real words, only the steps.
- A single word is a ladder (there is nothing to break). An empty list is not.
Tips
- In
one_letter_apart, count the differences in a loop:if a[i] != b[i]: count += 1. - Write
one_letter_apartfirst, then use it insideis_ladder. Small functions that each do one job are easier to get right. - In
is_ladder, loop overrange(1, len(words))so thatwords[i - 1]is always the word before. - You can
return Falsefrom inside a loop as soon as you find a bad step.