Python OOPE Exam
2024 Sep Oppe 1 Set 1
๐ Function: increment_value_with_max_limit
Here’s a function to increment the value for a given key in a dictionary, making sure it never exceeds a specified maximum limit!
def increment_value_with_max_limit(d, key, inc, limit):
"""
Increment the value of d[key] by inc, but do not let it exceed limit.
Args:
d (dict): Dictionary with integer values.
key: Key whose value you want to increment.
inc (int): The increment value.
limit (int): The maximum allowed value.
Returns:
None: The dictionary is modified in-place.
Example:
d = {'a': 5}
increment_value_with_max_limit(d, 'a', 10, 12)
# Now d['a'] == 12
"""
if key in d:
d[key] = min(d[key] + inc, limit)โจ Step-by-Step Explanation
- Check Key Exists: Make sure the key is present in the dictionary.
- Increment and Cap:
Add the
incvalue to the current value for the key. Usemin(new_value, limit)to cap the result atlimitif it would go over. - Update In Place: The original dictionary is modified directly. No return value necessary!
๐ Practice Questions
- If
d = {'x': 7}, what doesincrement_value_with_max_limit(d, 'x', 4, 10)do? - What happens for
d = {'b': 2},increment_value_with_max_limit(d, 'b', 5, 5)? - Try
d = {'score': 20},increment_value_with_max_limit(d, 'score', 3, 22)
โ Solutions
- The value becomes
min(7+4, 10) = 10. So,d['x']will be10. - The value becomes
min(2+5, 5) = 5. So,d['b']will be5. - The value becomes
min(20+3, 22) = 22. So,d['score']will be22.
๐ก Now you can safely increment dictionary values without ever exceeding the maximum you set!