Compute the overall conversion rate across segments of very different sizes
segments is a list of (conversions, visitors) pairs, one per segment. Return the overall conversion rate for all segments combined. The segments differ wildly in size — some have millions of visitors, some only a handful.
Return 0.0 when there are no visitors at all.
def overall_conversion(segments: list[tuple[int, int]]) -> float:
# your code here
Write the implementation.
Overall conversion is total conversions over total visitors — a size-weighted average — not the mean of the per-segment rates. Averaging the rates weights every segment equally, so a tiny high-rate segment skews the number; weighting by visitor count fixes it.
- ✗Averaging the per-segment rates as if the segments were equal size
- ✗Weighting by something other than visitor count
- ✗Ignoring that a small segment can swing the simple mean
- →When does the simple mean equal the weighted mean?
- →How would you weight by revenue instead of visitors?
Sum the conversions and sum the visitors across all segments, then divide — this is the size-weighted average. Never average the per-segment rates directly.
def overall_conversion(segments):
total_conv = sum(c for c, v in segments)
total_vis = sum(v for c, v in segments)
return total_conv / total_vis if total_vis else 0.0
For [(5, 10), (900, 10000)] the weighted rate is 905 / 10010 ≈ 0.0904. The simple mean of the rates would be (0.5 + 0.09) / 2 ≈ 0.295 — more than triple the truth, because the 10-visitor segment is given the same weight as the 10 000-visitor one.