Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Count word frequencies in a sentence

Count how many times each word appears in a sentence, normalizing case and ignoring punctuation.

Python practice15 minString PatternsIntermediateLast updated March 18, 2026

Problem statement

Given an input sentence (string), count the frequency of each word. The function should: - Treat uppercase and lowercase letters as the same (case-insensitive). - Ignore punctuation characters (consider only letters and digits when forming words). - Return the result as a list of (word, count) tuples sorted alphabetically by word (so the output ordering is deterministic). This representation (sorted list of tuples) ensures predictable outputs for testing and further processing.

Task

Write a function that extracts words from a sentence, counts occurrences, and returns a stable sorted list of (word, count) pairs.

Examples

Basic counting

Input

Hello, hello world!

Output

[('hello', 2), ('world', 1)]

The function lowercases words, strips punctuation and counts occurrences. 'hello' appears twice, 'world' once; sorted alphabetically.

Input format

A single string representing the sentence.

Output format

A list of (word, count) tuples sorted alphabetically by word.

Constraints

Sentence length up to a few thousand characters. Words consist of letters and digits; treat other characters as separators. You may use Python standard library (re, collections).

Samples

Sample 1

Input

One fish two fish

Output

[('fish', 2), ('one', 1), ('two', 1)]

Counts words and sorts result alphabetically.