Problem Set 5: Word Counter — Count the number of words in a sentence

When you start a new problem set, your first instinct might be to open your computer and begin typing code right away. While this can feel productive, it often leads to frustration when things don't work as expected. Instead, take a few minutes to slow down and plan.

Here are some helpful strategies:

  1. Understand the problem clearly
    • Read the instructions carefully — twice if needed.
    • Ask yourself: What exactly is being asked?
  2. Break the problem into smaller steps
    • Think about the smallest possible actions the computer will need to perform.
    • For example: If the task is to find the first recurring letter in a word, what steps must happen first?
  3. Try solving it on paper first
    • Write out your steps in plain language (pseudocode).
    • Test your steps with a simple example before touching the keyboard.
  4. Translate your steps into code
    • Start small — write only a few lines at a time and test often.
    • Don't worry about perfection at first; get a working version, then improve it.
  5. Check your solution
    • Run it with different examples, including edge cases.
    • Ask: Does this solve the problem in all situations?

  • Read the question carefully (twice).
  • Break the task into the smallest steps.
  • Sketch or write pseudocode before coding.
  • Start small — test as you go.
  • Check your solution with different cases.

Overview

Write a function that takes a sentence as input and returns how many words it contains.

  • Words are separated by spaces.
  • Ignore extra spaces at the beginning, end, or between words.

 

Learning objectives

You should be able to:

  • Use string methods to split text.
  • Handle multiple spaces.
  • Write a simple function that returns a number.

 

Success criteria

  • word_count(sentence) returns an integer.
  • Works with normal sentences.
  • Handles multiple spaces cleanly.
  • Returns 0 if the sentence is empty or only spaces.

Skeleton (Python) — word_counter.py

def word_count(sentence: str) -> int:
    """Return the number of words in the sentence.
    Words are separated by spaces. Ignore extra spaces.
    """
    if not isinstance(sentence, str):
        raise ValueError("Input must be a string")

    # Remove leading/trailing whitespace
    sentence = sentence.strip()
    if not sentence:
        return 0

    # Split by spaces and filter out empties
    words = [w for w in sentence.split(" ") if w]
    return len(words)

Manual examples

>>> from word_counter import word_count
>>> word_count("Hello world")
2
>>> word_count("   This   has   extra spaces   ")
4
>>> word_count("")
0

 

Tests — test_word_counter.py

from word_counter import word_count
import pytest

def test_basic():
    assert word_count("Hello world") == 2

def test_extra_spaces():
    assert word_count("   Too   many   spaces   here   ") == 4

def test_empty_string():
    assert word_count("") == 0

def test_only_spaces():
    assert word_count("     ") == 0

def test_single_word():
    assert word_count("Python") == 1

 

Stretch goals (optional)

  1. Handle punctuation better: "Hello, world!" → 2 words.
  2. Count unique words instead of total words.
  3. Return both the number of words and the list of words.