📘
Document Term Matrix
Given multiple documents (one per line), build a document-term matrix where each row represents a document and each column represents a unique word from the vocabulary.
The vocabulary should be sorted alphabetically. Each cell contains the count of that word in that document. All words should be lowercased.
Input format:
- Line 1: Number of documents n
- Lines 2 to n+1: One document per line
Output: Print each row of the matrix as a list of integers.
Example:
Input:
2 the cat sat the dog sat
Output:
[1, 0, 1, 1] [0, 1, 1, 1]
Reasoning:
Step 1: Collect vocabulary All unique words (sorted): ["cat", "dog", "sat", "the"]
Step 2: Count words per document Doc 1 "the cat sat": cat=1, dog=0, sat=1, the=1 → [1, 0, 1, 1] Doc 2 "the dog sat": cat=0, dog=1, sat=1, the=1 → [0, 1, 1, 1]
Constraints:
- 1 ≤ n ≤ 10
- Words are separated by spaces
- Convert all words to lowercase
- Vocabulary sorted alphabetically
- Output each row as a Python list of integers
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.