PIXELBANKv9.1.0
Menu

Build a Bag of Words (BoW) representation from a list of documents.

  1. Build a vocabulary of unique words across all documents (sorted alphabetically)
  2. For each document, create a vector where each element is the count of the corresponding vocabulary word

Words are split by spaces and converted to lowercase. Return the vocabulary list and the BoW matrix.

Example:

Input:
documents = ["the cat sat", "the dog sat", "the cat"]
Output:
(['cat', 'dog', 'sat', 'the'], [[1, 0, 1, 1], [0, 1, 1, 1], [1, 0, 0, 1]])
Reasoning:
  • The vocabulary is built by splitting each document into words, converting them to lowercase, and combining the results into a sorted list of unique words: ['cat', 'dog', 'sat', 'the'].
  • For each document, a vector is created where each element is the count of the corresponding vocabulary word. For the first document "the cat sat", this results in [1, 0, 1, 1] because it contains one 'cat', zero 'dog', one 'sat', and one 'the'.
  • The same process is applied to the remaining documents: the second document "the dog sat" becomes [0, 1, 1, 1], and the third document "the cat" becomes [1, 0, 0, 1].
  • The final output is a tuple containing the vocabulary list and the Bag of Words matrix: (['cat', 'dog', 'sat', 'the'], [[1, 0, 1, 1], [0, 1, 1, 1], [1, 0, 0, 1]]).

Constraints:

  • documents: list of strings
  • Split on spaces, convert to lowercase
  • Vocabulary is sorted alphabetically
  • Return tuple (vocabulary, bow_matrix)
  • bow_matrix: 2D list (n_docs x vocab_size)
solution.py

Test Results

0/0
Run code to see test results.
Bag of Words - Easy | PixelBank