question 209 Dates Numbers & Regex · hard
Spread a discount across order lines
A 10.00 coupon applies to a whole order, but the accounts system books discounts per line. Spread the discount across the lines in proportion to their totals, in whole cents, so the line discounts add up to exactly the coupon.
Function
allocate_discount(line_totals, discount)Inputsline totals and the discount as text with two decimals, e.g.
["43.77", "50.57", "39.09"] and "10.00"; the order total is above 0Step 1each line's exact share is
discount × line_total ÷ order_total; round every share down to the centStep 2hand the leftover cents out one at a time to the lines whose shares lost the most in rounding (the largest remainders); on a tie, the earlier line first
Returnsa list of texts with two decimals, one per line, that add up exactly to
discountExamples
callallocate_discount(['43.77', '50.57', '39.09'], '10.00')returns['3.28', '3.79', '2.93']
callallocate_discount(['12.93'], '5.00')returns['5.00']
callallocate_discount(['10.00', '10.00', '10.00'], '1.00')returns['0.34', '0.33', '0.33']