Bigrams from a sentence
Python data engineering interview problem. Difficulty: beginner. Pattern: Strings. About 8 minutes. Free to practice.
Build pairs of consecutive words after lowercasing and removing punctuation. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
Text pipelines often turn a sentence into adjacent word pairs for search or language statistics. Lowercase the text, remove punctuation, split on whitespace and return every consecutive pair as a tuple. Fewer than 2 words gives an empty list. Write bigrams(text: str) -> list[tuple]. Hello, World! Hello becomes words hello, world, hello and pairs ('hello','world') and ('world','hello'). The starter file already contains the function name, harness and print lines. Keep them and fill only the function body.
Requirements
- Normalize case before building pairs.
- Remove punctuation characters.
- Keep pair order and use tuples.
Constraints
- Punctuation does not become a word.
- The return type is a list of 2-item tuples.
Examples
Input: bigrams("Hello, World! Hello") Output: [('hello', 'world'), ('world', 'hello')] After lowercasing and removing punctuation the words are hello, world, hello.
Topics: lakebench, python, tokenize, n-grams.
More Python interview questions · All interview problems · Learn data engineering
Bigrams from a sentence
Interview-style drill: Build pairs of consecutive words after lowercasing and removing punctuation.
Implement `bigrams(text: str) -> list[tuple]`. Lowercase the text, remove every punctuation character (such as `, . ! ? ' -`), split it into words on whitespace and return the pairs of consecutive words as tuples, in order. A token that is only punctuation disappears. Fewer than 2 words gives an empty list. Example: `"The cat sat."` gives `[('the', 'cat'), ('cat', 'sat')]`.