Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Annotated "Convert and Aggregate" solution in Clear category for Convert and Aggregate by BootzenKatzen
"""
This one was tricky for me, because I didn't know much about dictionaries in python to begin with.
I think I had about 7 tabs open trying to figure out the best way to do this (for me at least)
I'm sure there are much more elegant solutions but this is what I came up with
I tried to figure out some ways to compact it, but it just wasn't working for me today
"""
def conv_aggr(data: list[tuple[str, int]]) -> dict[str, int]:
mydict = {} # creating the dictionary to add to
for a, b in data: # iterating through the tuples in the list
if a != '': # we want to skip any tuples where the key is ''
if a in mydict: # if the key is already in the dictionary
mydict[a] = mydict[a] + b # we add our new value to the value already existing in the dictionary
# under the same key
else: # if it's not already in the dictionary
mydict[a] = b # we add it to the dictionary
if mydict[a] == 0: # if the value for this key equals 0
del mydict[a] # we remove this entry from the dictionary
return mydict
print("Example:")
print(conv_aggr([("a", 7), ("b", 8), ("a", 10)]))
# These "asserts" are used for self-checking
assert conv_aggr([("a", 7), ("b", 8), ("a", 10)]) == {"a": 17, "b": 8}
assert conv_aggr([]) == {}
assert conv_aggr([("a", 5), ("a", -5)]) == {}
assert conv_aggr([("a", 5), ("a", 5), ("a", 0)]) == {"a": 10}
assert conv_aggr([("a", 5), ("", 15)]) == {"a": 5}
print("The mission is done! Click 'Check Solution' to earn rewards!")
April 13, 2023
Comments: