📘
Bag of Words
Build a Bag-of-Words (BoW) representation for a corpus of documents.
Algorithm:
- Build a vocabulary: collect all unique words across all documents, sorted alphabetically
- For each document, create a vector where each element is the count of the corresponding vocabulary word in that document
Input format:
- Line 1: Number of documents N
- Lines 2 to N+1: One document per line (lowercase, space-separated words)
Output:
- Line 1: The vocabulary (sorted list of unique words)
- Line 2: The BoW matrix (list of lists, one per document)
Example:
Input:
3 the cat sat the dog sat the cat and the dog
Output:
['and', 'cat', 'dog', 'sat', 'the'] [[0, 1, 0, 1, 1], [0, 0, 1, 1, 1], [1, 1, 1, 0, 2]]
Reasoning:
Step 1: Build vocabulary All unique words: {"the", "cat", "sat", "dog", "and"} Sorted: ["and", "cat", "dog", "sat", "the"]
Step 2: Count words per document
- Doc 0 "the cat sat": and=0, cat=1, dog=0, sat=1, the=1 => [0,1,0,1,1]
- Doc 1 "the dog sat": and=0, cat=0, dog=1, sat=1, the=1 => [0,0,1,1,1]
- Doc 2 "the cat and the dog": and=1, cat=1, dog=1, sat=0, the=2 => [1,1,1,0,2]
Constraints:
- All words are already lowercase
- Vocabulary is sorted alphabetically
- Each row of the BoW matrix corresponds to a document
- Each column corresponds to a vocabulary word
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.