Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Aggregate by Operation by vtflnk
from collections import defaultdict
from collections import namedtuple
OperationCode = namedtuple("OperationCode", "PLUS MINUS MULT DIV LET")
codes = OperationCode('+', '-', '*', '/', '=')
def aggr_operation(data: list[tuple[str, int]]) -> dict[str, int]:
d = defaultdict(int)
for key, value in data:
if not (key1 := key[1:]):
continue
match key:
case key if key[0] == codes.PLUS:
d[key1] += value
case key if key[0] == codes.MINUS:
d[key1] -= value
case key if key[0] == codes.MULT:
d[key1] *= value
case key if key[0] == codes.DIV:
if value:
d[key1] /= value
case key if key[0] == codes.LET:
d[key1] = value
if not d[key1]:
d.pop(key1)
return d
print("Example:")
print(aggr_operation([("+a", 7), ("-b", 8), ("*a", 10)]))
# These "asserts" are used for self-checking
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!")
Jan. 2, 2023