Problem 328032 · easy · Level 03 Linear Management & Searching

One Number to Bake Every Day

py-higher-order · lambda · loss functions · min with key

A bakery wants to bake the same number of cakes every day. For a candidate number c, the cost of a day on which a cakes were sold is loss(c, a), and the cost of a candidate is the total over all days. Different managers measure the cost differently, so loss is a function that the caller passes in.

Write best_constant(sold, candidates, loss) that returns the candidate with the smallest total cost. If several candidates tie, return the smallest of them.

The tests pass their own loss functions, for example lambda c, a: (c - a) ** 2, and the helper daily_sales(n, seed) generates n days of sales (try it with Run).

Examples

Input:  sold = [3, 5, 10], candidates = [3, 4, 5, 6, 7], loss = lambda c, a: (c - a) ** 2
Output: 6
Explanation: The totals are 53, 38, 29, 26 and 29.

Input:  sold = [3, 5, 10], candidates = [3, 4, 5, 6, 7], loss = lambda c, a: abs(c - a)
Output: 5

Constraints

  • 1 <= len(sold) <= 2000, 1 <= len(candidates) <= 200.
  • loss returns a number (an int, float or bool).

Goals

  • Write a function that takes another function as an argument
  • Call the function you were given instead of hard-coding one formula
  • See how the choice of loss changes the best prediction
Starting Python…