Brightest Squares

Data with PythonHard+10 XP+10

Brightest Squares

A heatmap with many columns has dozens of squares. An analyst wants a short list of the pairs worth a closer look: the ones that move together most strongly, whether up or down.

Task: write strongest_pairs(columns, k). columns is a dictionary mapping each column name to its list of numbers (all lists have the same length).

Return a list of up to k entries [name_a, name_b, r]:

  • Each pair of different columns appears once, with name_a before name_b alphabetically. Never pair a column with itself.
  • r is their correlation rounded to 2 decimal places.
  • Order the pairs by the size of the rounded r, ignoring its sign, largest first. So -0.9 comes before 0.8.
  • Break ties alphabetically by name_a, then by name_b.
  • If there are fewer than k pairs, return them all.

There are at least two columns, no missing values, and no column holds the same value in every row.

Examples

columns = {"rain": [5, 1, 7, 2, 4], "umbrellas": [40, 8, 52, 20, 33], "ice_cream": [10, 30, 4, 25, 12]}
k = 2
returns [['ice_cream', 'umbrellas', -0.99], ['rain', 'umbrellas', 0.99]]
columns = {"b": [1, 2, 3], "a": [3, 1, 2]}
k = 5
returns [['a', 'b', -0.5]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run