Calculate Shipping Cost
Order:
{
"country": "US", // or "CA" for the CA order
"items": [{ "product": "mouse", "quantity": 20},
{"product": "laptop", "quantity": 5}
]
}
Note: In your solution, you can pass in an in-memory object that has the same shape as the JSON. You don’t need to worry about parsing JSON for this problem.
The US and CA orders have the same shape; they are just different countries.
Each country/product has a corresponding shipping cost matrix. The cost is stored in the smallest currency unit.
Shipping Cost:
Each product has its own shipping cost
{
"US": [{ "product": "mouse", "cost": 550},
{"product": "laptop", "cost": 1000}
],
"CA": [{ "product": "mouse", "cost": 750},
{"product": "laptop", "cost": 1100}
]
}
Write a function called calculate_shipping_cost that takes an order and shipping cost matrix and returns the shipping cost.
Examples:
calculate_shipping_cost(order_us, shipping_cost) == 16000
calculate_shipping_cost(order_ca, shipping_cost) == 20500
这道题要求根据订单中的国家、商品和数量,结合对应国家的运费表计算总运费。核心做法是先按国家找到该国的商品运费,再按商品名建立快速查询结构,遍历订单 items 时把每个商品的单价乘以数量累加即可。题目里金额使用最小货币单位,所以直接做整数加法,不需要处理小数;示例中 US 和 CA 的同一商品单价不同,因此要先区分 country 再计算。