The Best Basket Money Can Buy

utility · budget constraint · exhaustive search · tie-breaking

A utility function U(x, y) scores how much a shopper likes a bundle of x units of one good and y units of another: a higher number means a preferred bundle. A shopper with income coins, facing prices px and py, picks the affordable bundle (whole units, at least 0, with p_x x + p_y y \le income) of highest utility.

Write best_basket(income, px, py, utility) that returns that bundle as a tuple (x, y). utility is a function: call utility(x, y) to score a bundle. If several affordable bundles share the highest utility, the shopper keeps her money: return the cheapest of them, and if several of those cost the same, the one with the most x.

The tests use these utility functions, all defined for you (try them with Run):

name U(x, y)
product_taste x \cdot y
basics_taste (x + 1)(y + 2)
pairs_taste \min(2x, y)
swap_taste 3x + 2y
any_four_taste \min(x + y, 4)
treat_taste x^2 + y
enough_taste 10x - x^2 + 8y - y^2

Examples

Input:  income = 12, px = 2, py = 3, utility = product_taste
Output: (3, 2)
Explanation: 3 * 2 = 6 for exactly 12 coins; no other affordable bundle scores 6 or more.

Input:  income = 12, px = 1, py = 3, utility = any_four_taste
Output: (4, 0)
Explanation: many bundles score 4, such as (0, 4) for 12 coins, but (4, 0) costs only 4.

Input:  income = 6, px = 3, py = 2, utility = swap_taste
Output: (2, 0)
Explanation: (2, 0) and (0, 3) both score 6 and both cost 6; (2, 0) has more x.

Constraints

  • every utility in the tests returns a whole number, so equal scores are exactly equal

Goals

  • Search every affordable whole-unit bundle for the highest utility
  • Pass a utility function as an argument and call it on each bundle
  • Apply a stated tie rule: cheapest first, then more of the first good
Starting Python…