Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
match..case solution in Clear category for Aggregate by Operation by mu_py
def aggr_operation(data: list[tuple[str, int]]) -> dict[str, int]:
result={}
for k, val in data:
op, key = k[0:1], k[1:]
if not key: continue
match op:
case '*': result[key] = result.setdefault(key,0) * val
case '/': result[key] = result.setdefault(key,0) / (val if val else 1)
case '+': result[key] = result.setdefault(key,0) + val
case '-': result[key] = result.setdefault(key,0) - val
case '=': result[key] = val
if not result[key]: del result[key]
return result
print("Examples:")
print(aggr_operation([("+a", 7), ("+a", 8), ("*a", 10)]))
print(aggr_operation([("+a", 7), ("*a", 0)]))
print('Asserts')
assert aggr_operation([("+a", 7), ("-b", 8), ("*a", 10)]) == {"a": 70, "b": -8}
assert aggr_operation([]) == {}
assert aggr_operation([("+a", 5), ("+a", -5), ("-a", 5), ("-a", -5)]) == {}
assert aggr_operation([("*a", 0), ("=a", 0), ("/a", 0), ("-a", -5)]) == {"a": 5}
print("The mission is done! Click 'Check Solution' to earn rewards!")
Sept. 18, 2022