🛠️ToolsShed

Price Per Unit Comparison

Compare products by price per unit to find the best value when shopping.

PricePerUnitComparison.product 1
Price per Unit/g
0.007980
PricePerUnitComparison.product 2
Price per Unit/g
0.006490Best Value
PricePerUnitComparison.product 3
Price per Unit/g
0.007633

PricePerUnitComparison.summary

Product NamePriceQuantityPrice per Unit
Brand B6.491 kg0.006490/g
Brand C2.29300 g0.007633/g
Brand A3.99500 g0.007980/g

Häufig gestellte Fragen

Code-Implementierung

def price_per_unit(price: float, quantity: float, unit: str) -> float:
    """Calculate price per base unit (grams or ml)."""
    conversions = {
        'g': 1, 'kg': 1000, 'oz': 28.3495, 'lb': 453.592,
        'ml': 1, 'l': 1000, 'fl oz': 29.5735, 'pt': 473.176,
    }
    factor = conversions.get(unit.lower(), 1)
    base_qty = quantity * factor
    return price / base_qty if base_qty > 0 else float('inf')

products = [
    {"name": "Brand A", "price": 2.99, "quantity": 500, "unit": "g"},
    {"name": "Brand B", "price": 4.49, "quantity": 1,   "unit": "kg"},
    {"name": "Brand C", "price": 1.79, "quantity": 12,  "unit": "oz"},
]

results = [(p["name"], price_per_unit(p["price"], p["quantity"], p["unit"])) for p in products]
results.sort(key=lambda x: x[1])

print("Price per gram (sorted cheapest first):")
for name, ppu in results:
    print(f"  {name}: ${ppu*100:.4f} per 100g")

best = results[0]
print(f"\nBest value: {best[0]}")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.