S1Q3 · Increment Dict Value with Max Limit¶
⚡ Quick Reference
Function: increment_value_with_max_limit(d, key, inc, limit) -> None
Core idea: add inc to d[key], cap at limit using min().
def increment_value_with_max_limit(d: dict, key: str, inc: int, limit: int):
d[key] = min(d[key] + inc, limit)
Key rules:
- Modifies d in-place - returns None
- min(current + inc, limit) caps the result automatically
- Works for any increment, including when result is below limit
Problem Statement¶
Problem
Write a function increment_value_with_max_limit(d, key, inc, limit) that increments d[key] by inc, but caps it at limit. Modifies in-place, returns None.
Examples:
d={"x":5,"y":3,"z":5}, key="y", inc=5, limit=5
{"x": 5, "y": 5, "z": 5}
3 + 5 = 8 > 5 → capped at 5
key="z", inc=5, limit=11
10
5 + 5 = 10 < 11 → no cap, stays 10
Solution approaches¶
Key takeaways¶
min() as a natural cap
min(value, ceiling) enforces an upper bound. The mirror - max(value, floor) - enforces a lower bound. Combine: min(max(v, lo), hi) clamps to a range.
In-place dict modification
d[key] = new_value modifies the dict the caller passed in. No return needed. Always check whether a problem wants in-place modification or a new return value.
Two-step: compute then cap
Think of it as two separate operations: d[key] + inc (increment), then min(..., limit) (cap). Naming them separately in the explanatory approach makes debugging easier.