Problem 242338 · medium · Level 02 Linear Data Structures

One Number for Every Day

best constant prediction · mean · median · squared error · absolute error

A café bakes the same number of croissants every day and wants that number to be as good as possible for the past sales sales (one number per day). "Good" depends on how a miss is scored:

  • under the squared error, a guess c costs the average of (c - s) ** 2 over the days;
  • under the absolute error, it costs the average of abs(c - s).

Write best_constants(sales) that returns a tuple (c_sq, loss_sq, (lo, hi), loss_abs):

  • c_sq is the constant (any real number) with the smallest average squared error, and loss_sq that error;
  • every constant from lo to hi (inclusive) has the smallest average absolute error, and no other constant does; loss_abs is that error.

c_sq, loss_sq and loss_abs are floats; lo and hi are values from sales.

Examples

Input:  sales = [30, 42, 35, 38, 90]
Output: (47.0, 477.6, (38, 38), 13.4)
Explanation: the day with 90 sales (a festival) pulls the best squared-error guess up to 47.
The best absolute-error guess is 38; it misses by 8, 4, 3, 0 and 52, on average 13.4.

Input:  sales = [4, 10, 6, 1]
Output: (5.25, 10.6875, (4, 6), 2.75)
Explanation: any guess from 4 to 6 misses by 11 in total, for example 5: 1 + 5 + 1 + 4.

Constraints

  • 1 <= len(sales) <= 10**5; sales are whole numbers from 0 to 10**4

Goals

  • Find the constant prediction with the smallest squared error and the one with the smallest absolute error
  • See that the mean and the median are the answers to two optimisation problems
  • Recognise that the absolute error can have a whole interval of best constants
Starting Python…