S1Q1 · Compute Electricity Bill¶
⚡ Quick Reference
Function: compute_electricity_bill(units: int) -> float
Core idea: three-slab billing - each slab has a per-unit rate and an optional fixed charge.
def compute_electricity_bill(units: int) -> float:
if units <= 200:
cost = units * 0.5
elif units <= 400:
cost = units * 0.75 + 150
else:
cost = units * 0.90 + 300
return cost
Key rules:
- ≤ 200 units → 0.5 per unit, no fixed charge
- ≤ 400 units → 0.75 per unit + 150 fixed
- > 400 units → 0.90 per unit + 300 fixed
Problem Statement¶
Problem
Write a function compute_electricity_bill(units) that returns the total electricity bill based on the slab rates.
Examples:
200
100.0
412
670.8
Problem statement error
The problem states compute_electricity_bill(210) -> 236.50. This is incorrect - no formula consistent with the given rates produces 236.50 for 210 units. The flat-rate formula gives 210 × 0.75 + 150 = 307.50. The correct answer for 210 units is 307.50.
Tracing all examples¶
units |
Slab | Formula | Result |
|---|---|---|---|
| 200 | ≤ 200 | 200 × 0.5 |
100.0 ✓ |
| 210 | ≤ 400 | 210 × 0.75 + 150 |
307.5 |
| 412 | > 400 | 412 × 0.90 + 300 |
670.8 ✓ |
Solution approaches¶
Key takeaways¶
if-elif chain - check lower slabs first
Since elif units <= 400 only runs when units > 200 (the first condition already failed), the slabs don't overlap. Always order conditions from lowest to highest slab boundary.
Flat rate vs tiered billing
This problem uses a flat rate - the rate applies to all units, not just the units above the previous threshold. `210 × 0.75 + 150` charges 0.75 per unit for all 210 units. Tiered billing (like income tax) would only charge 0.75 on the extra 10 units.
Return float - don't truncate
The template's return cost suggests the result should be a float. Python arithmetic with 0.5, 0.75, 0.90 already produces floats - no explicit conversion needed.