🛠️ToolsShed

Kalkulator Harga Satuan

Bandingkan harga per satuan untuk menemukan penawaran terbaik di antara ukuran kemasan yang berbeda.

Item 1
Item 2

Pertanyaan yang Sering Diajukan

Implementasi Kode

# Unit Price Calculator — find the best value

def unit_price(price, quantity, unit="g"):
    """Calculate price per unit."""
    return price / quantity

def compare_products(products):
    """
    products: list of dicts with 'name', 'price', 'quantity', 'unit'
    Returns products sorted by unit price (best value first).
    """
    results = []
    for p in products:
        up = unit_price(p["price"], p["quantity"])
        results.append({**p, "unit_price": up})
    return sorted(results, key=lambda x: x["unit_price"])

# Example: comparing 3 coffee products
products = [
    {"name": "Brand A 200g", "price": 3.99, "quantity": 200, "unit": "g"},
    {"name": "Brand B 500g", "price": 8.49, "quantity": 500, "unit": "g"},
    {"name": "Brand C 1kg",  "price": 15.99, "quantity": 1000, "unit": "g"},
]

ranked = compare_products(products)
for i, p in enumerate(ranked, 1):
    print(f"{i}. {p['name']}: ${p['unit_price']*100:.4f} per 100{p['unit']}")

# Output:
# 1. Brand C 1kg: $1.5990 per 100g  (best value)
# 2. Brand A 200g: $1.9950 per 100g
# 3. Brand B 500g: $1.6980 per 100g

Comments & Feedback

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