Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second solution in Clear category for Aggregate by Operation by diwert-ai
def do_calc(x, y, op):
if op == '+':
x += y
elif op == '-':
x -= y
elif op == '*':
x *= y
elif op == '/':
x = x/y if y else x
elif op == '=':
x = y
return x
def aggr_operation(data: list[tuple[str, int]]) -> dict[str, int]:
result = dict()
for expression, value in data:
op, key = expression[0], expression[1:]
result.update({key: do_calc(result.get(key, 0), value, op)}) if key else None
return {key: result[key] for key in result if result[key] != 0}
print("Example:")
print(aggr_operation([("+a", 7), ("-b", 8), ("*a", 10)]))
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. 17, 2022
Comments: