Lesson 6 of 8 · 12 min

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:

  1. one_letter_apart(a, b) returns True if the two words have the same length and differ in exactly one position, otherwise False.
  2. is_ladder(words) returns True if 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: dog and god differ 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_apart first, then use it inside is_ladder. Small functions that each do one job are easier to get right.
  • In is_ladder, loop over range(1, len(words)) so that words[i - 1] is always the word before.
  • You can return False from inside a loop as soon as you find a bad step.
main.py
def one_letter_apart(a, b):
    # TODO: same length, and exactly one position different
    return False


def is_ladder(words):
    # TODO: check every step with one_letter_apart
    return False


print(is_ladder(["cold", "cord", "card", "ward", "warm"]))  # should print True

Python 3.14 runs right here in your browser. The first run downloads about 10 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…