from math import inf
class BuyerMarketplace:
def __init__(self, datastore: Datastore):
self.ds = datastore
def buy_items(self, buyer_name: str, wants: dict[str, int]) -> dict[str, Item]:
listings = self.ds.get_all()
# cheapest unsold listing per item_name
cheapest: dict[str, Item] = {}
cheapest_price: dict[str, float] = {}
for it in listings:
if it.buyer_name: # skip sold
continue
p = it.price
name = it.item_name
if name not in cheapest_price or p < cheapest_price[name]:
cheapest_price[name] = p
cheapest[name] = it
result: dict[str, Item] = {}
for name, max_price in wants.items():
if name in cheapest and cheapest_price[name] <= max_price:
it = cheapest[name]
trade = Item(it.seller_name, buyer_name, name, cheapest_price[name])
self.ds.put(trade) # persist sale
result[name] = trade
return result