Problem 154896 · medium · Level 01 Prerequisites & Setup

Columns That Say the Same Thing

vectors · columns · dot product · cosine similarity · exact arithmetic

A shop exports a product table with one row per product and many columns. Some columns are copies in disguise: length in mm is always 10 times length in cm, pairs sold is half of shoes sold, loss is minus profit. Such a column adds nothing a model could learn from, only extra work.

Two columns are copycats when one is a fixed non-zero multiple of the other, the same multiple in every row (the multiple may be negative or a fraction). Write copycat_groups(rows) that returns the groups of columns that are all copycats of each other:

  • each group is a list of column indices in increasing order, with at least 2 columns,
  • the groups are ordered by their first index,
  • columns that have no copycat do not appear.

Examples

Input:  rows = [[2, 20, 5, -2],
                [3, 30, 1, -3],
                [1, 10, 4, -1]]
Output: [[0, 1, 3]]
Explanation: column 1 is 10 times column 0 and column 3 is -1 times column 0. Column 2 is not
a multiple of any other column.

Input:  rows = [[1, 2, 3, 6], [2, 4, 1, 2]]
Output: [[0, 1], [2, 3]]

Constraints

  • 1 <= len(rows) <= 1000, every row has the same length d with 1 <= d <= 20
  • every value is a whole number between -1000 and 1000, and no column is all zeros

Goals

  • Treat each column of a dataset as a vector of its own
  • Recognise that one column is a multiple of another exactly when their cosine is 1 or -1
  • Test that condition with whole numbers so no rounding can hide it
Starting Python…