Skip to content
Laviyx Learn

Try

Python Lab · Experiment 17

Add single-letter words and the empty string to a word list

PythonWeek 4JNTUH R22 · CS206ES

Aim

To write a Python program that reads a word list from the file words.txt into a set, adds the single-letter words "i" and "a" and the empty string to it, and uses the list to find whether a word can be reduced, one letter at a time, to the empty string with every step being a valid word.

Algorithm

  1. Open words.txt and read each line into a set, removing spaces and converting to lowercase. If the file is missing, print a message and stop.
  2. Show that "i" and "a" are not in the list yet.
  3. Add "i", "a" and the empty string "" to the set.
  4. Read a word from the keyboard. If it is not in the word list, say so and stop.
  5. Define a recursive function reduce_word(word). If the word is "", return [""].
  6. Otherwise, for each position, remove that one letter. If the shorter word is in the set and can itself be reduced, return the word followed by that chain.
  7. If no letter can be removed this way, return None.
  8. Print the chain of words, or say that the word cannot be reduced.

Program

Python
def load_words(filename):
    """Read one word per line from the file into a set."""
    words = set()
    with open(filename) as f:
        for line in f:
            word = line.strip().lower()
            if word:
                words.add(word)
    return words


def reduce_word(word, words):
    """Return a list of words from word down to "", or None."""
    if word == "":
        return [""]
    for i in range(len(word)):
        child = word[:i] + word[i + 1:]  # word with letter i removed
        if child in words:
            chain = reduce_word(child, words)
            if chain is not None:
                return [word] + chain
    return None


try:
    words = load_words("words.txt")
except FileNotFoundError:
    print("words.txt not found")
else:
    print("Words read from words.txt:", len(words))
    print("Is 'i' in the list?", "i" in words)
    print("Is 'a' in the list?", "a" in words)

    words.add("i")
    words.add("a")
    words.add("")
    print("Added 'i', 'a' and the empty string. Words now:", len(words))
    print()

    word = input("Enter a word: ").strip().lower()
    if word not in words:
        print(f"'{word}' is not in the word list")
    else:
        chain = reduce_word(word, words)
        if chain is None:
            print(f"'{word}' cannot be reduced to the empty string")
        else:
            shown = [w if w else '""' for w in chain]
            print("Reduced:", " -> ".join(shown))

Output

A word that can be reduced

Input file: words.txt (Text)
it
pit
spit
spite
sprite
print
pint
python
as
Output 1
Words read from words.txt: 9
Is 'i' in the list? False
Is 'a' in the list? False
Added 'i', 'a' and the empty string. Words now: 12

Enter a word: sprite
Reduced: sprite -> spite -> spit -> pit -> it -> i -> ""

A word that cannot be reduced

Input file: words.txt (Text)
it
pit
spit
spite
sprite
print
pint
python
as
Output 2
Words read from words.txt: 9
Is 'i' in the list? False
Is 'a' in the list? False
Added 'i', 'a' and the empty string. Words now: 12

Enter a word: python
'python' cannot be reduced to the empty string

Recorded by running this exact program. Typed input appears after each prompt.

How it works

This item comes from an exercise in the book Think Python. The exercise uses a large file of English words, words.txt, and asks for words that can be made shorter one letter at a time while staying a real word at every step, for example sprite → spite → spit → pit → it → i. The book's word list has no one-letter words, so the last steps can never succeed. The syllabus line is the book's hint: add "I" and "a" (stored here in lowercase as "i" and "a") and the empty string, which acts as the final stop of every chain. The program does exactly that with a small words.txt; the real list has over 100,000 words and works the same way.

The words are kept in a set, so checking child in words is fast even for a large list.

reduce_word is recursive: to reduce "sprite" it only has to find one shorter word that can itself be reduced. The empty string is the base case that ends the recursion. Without adding "", the function would never find a complete chain.

Common mistakes

  • Reading the file without strip(). Each line keeps its newline, so "it\n" is stored and "it" in words is False.

  • Adding "I" in uppercase while the words are stored in lowercase. Convert everything to one case so the comparisons match.

  • Forgetting the base case word == "". The recursion then never stops at the empty string and no chain is ever found.

  • Storing the words in a list instead of a set. in on a list checks every element, which is very slow for a list of 100,000 words.

Viva questions

Try to answer each one aloud before you open it.

  • Why are single-letter words and the empty string added to the list?

    Every chain of shorter and shorter words must end with a one-letter word and then the empty string. The original word list has neither, so without them no word could ever be fully reduced.

  • Why is a set used to hold the words?

    Checking whether a value is in a set takes about the same short time however big the set is, while a list has to be searched item by item.

  • What is the base case of reduce_word?

    The empty string. When the word is "", the function returns [""] without calling itself again.

  • How do you remove the letter at position i from a string?

    Join the part before it and the part after it: word[:i] + word[i + 1:]. Strings cannot be changed in place, so this builds a new string.

  • What does the with statement do when opening a file?

    It closes the file automatically when the block ends, even if an error happens inside it.

Learn the concepts

All Python Programming Lab experiments →