Level 1 A flat price per unit
A shop charges shipping by country and product. An order is a list of lines (country, product, quantity), like ("US", "mouse", 20). A rate (country, product, price) says that shipping one unit of that product to that country costs price cents.
Write shipping_cost(order, rates) -> int: the total shipping cost of the order, in cents.
- Each line costs
quantity * pricefor its own(country, product)rate. The same product can cost different amounts in different countries. - Each
(country, product)pair has at most one rate. Names are case-sensitive. - If any line has no rate, the order can't be shipped: return
-1. This holds even for a line with quantity 0. - Quantities are 0 or more. An empty order costs 0.
rates = [("US", "mouse", 550), ("US", "laptop", 1000), ("CA", "mouse", 750)]
shipping_cost([("US", "mouse", 20), ("US", "laptop", 5), ("CA", "mouse", 3)], rates)
# 18250 = 20 * 550 + 5 * 1000 + 3 * 750
shipping_cost([("US", "mouse", 2), ("MX", "mouse", 1)], rates)
# -1: nothing ships to MX
Constraints: up to 10^5 lines and 10^5 rates. Quantities are at most 10^9 and the total always fits in a 64-bit integer. ⭐ Bonus: the speed test earns a star if each line finds its rate in O(1).