Quality Along the Bars

Data with PythonHard+10 XP+10

Quality Along the Bars

A histogram shows how many wines fall in each alcohol range. A sharper question is: how good are the wines in each bar?

Task: write quality_by_bin(path, column, bins). path is a CSV file that uses semicolons between values. Its header row holds the column names, including column and quality. There are no missing values, and every row counts — repeats included. The starter code includes write_text(path, text), which saves text into a file and returns the path; the tests use it to create each file.

Sort the rows into bins by their column value, using the same rule as ax.hist:

  • The bins split the range from the smallest to the largest value of column into bins bins of equal width.
  • A value exactly on the edge between two bins goes into the bin on its right.
  • The largest value goes into the last bin.

Return a list with one entry per bin, from the lowest bin to the highest. Each entry is [count, average]: how many rows landed in that bin (an int), and the average quality of those rows as a float rounded to 2 decimal places. A bin with no rows is [0, None].

column always holds at least two different values, and bins is at least 1.

Examples

path = write_text("bars_a.csv", '"alcohol";"quality"\n9.0;5\n9.5;5\n10.0;6\n11.0;6\n12.0;7\n13.0;8\n9.2;4\n')
column = "alcohol"
bins = 4
returns [[3, 4.67], [1, 6.0], [1, 6.0], [2, 7.5]]
path = write_text("bars_b.csv", '"sugar";"alcohol";"quality"\n1.0;9.4;5\n3.0;10.0;6\n2.0;11.0;6\n3.0;12.0;7\n')
column = "sugar"
bins = 2
returns [[1, 5.0], [3, 6.33]]

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