Fruit Weights
Source: Dec 2024, Task 6 (DTU 02002/02003). Study solution — not an official answer key.
Problem
Fruit names may differ only by case. Standardize keys to lowercase. If the same fruit appears multiple times, average the weights and round down (floor).
Write fruit_weights(table) returning the new dict (do not rely on mutating the input).
Example
>>> table = {'apple': 182, 'banana': 110, 'Orange': 160,
... 'Banana': 115, 'APPLE': 185, 'Apple': 175, 'lime': 67}
>>> fruit_weights(table)
{'apple': 180, 'banana': 112, 'orange': 160, 'lime': 67}
Approach
Group weights by name.lower(), then math.floor(sum / count) for each group.
Solution
Show solution Hide solution
Solution
import math
def fruit_weights(table):
sums = {}
counts = {}
order = []
for name, weight in table.items():
key = name.lower()
if key not in sums:
order.append(key)
sums[key] = 0
counts[key] = 0
sums[key] += weight
counts[key] += 1
return {k: math.floor(sums[k] / counts[k]) for k in order}