📅  最后修改于: 2023-12-03 15:25:50.948000             🧑  作者: Mango
在购买所有书籍时,我们可能会面临不知道该去哪里买或者哪个商家提供最优惠价格等问题。因此,我们需要编写一个程序来帮助我们寻找购买所有书籍的最低成本。
为了寻找购买所有书籍的最低成本,我们可以采用以下思路:
下面是一份Python代码示例:
def find_lowest_cost(books: dict) -> dict:
lowest_cost = float("inf")
book_prices = {}
for book in sorted(books, key=lambda x: books[x]):
for store, price in books[book].items():
if price < lowest_cost:
lowest_cost = price
book_prices[book] = (store, price)
return {"lowest_cost": lowest_cost, "book_prices": book_prices}
该函数接受一个字典作为参数,其中字典的键是书籍名称,值是一个字典,包括书籍在不同商家中的价格信息。通过遍历所有书籍并在每个商家中寻找书籍的最低价格,最终返回最低成本和每个书籍应该在哪个商家购买。
下面是使用示例:
books = {
"Python Crash Course": {"Amazon": 49.99, "Barnes & Noble": 55.66, "Walmart": 47.99},
"The Pragmatic Programmer": {"Amazon": 51.99, "Barnes & Noble": 50.99},
"Clean Code": {"Amazon": 35.99, "Barnes & Noble": 37.99, "Walmart": 33.99},
}
result = find_lowest_cost(books)
print(f"Lowest cost: ${result['lowest_cost']:.2f}")
for book, (store, price) in result["book_prices"].items():
print(f"{book} should be bought from {store} for ${price:.2f}")
输出:
Lowest cost: $33.99
Python Crash Course should be bought from Walmart for $47.99
The Pragmatic Programmer should be bought from Barnes & Noble for $50.99
Clean Code should be bought from Walmart for $33.99
该程序在输入所有书籍的名称和对应的商家及价格后,输出了最低成本和每个书籍应该在哪个商家购买。