Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Symbol map with lambdas, a bit wordy solution in Clear category for Aggregate by Operation by kkkkk
from collections import defaultdict
symbol_map = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y,
"=": lambda x, y: y,
}
def aggr_operation(data: list[tuple[str, int]]) -> dict[str, int]:
"""Convert tuples to dict using operation in key and matching tuples."""
conversion = defaultdict(int)
for key, value in data:
if len(key) < 2:
continue
operation, key = key[0], key[1:]
if key:
try:
conversion[key] = symbol_map[operation](conversion[key], value)
except ZeroDivisionError:
pass
if not conversion[key]:
del conversion[key]
return conversion
Oct. 1, 2022
Comments: