Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Annotated for Understanding solution in Clear category for Sum by Type by BootzenKatzen
# This is my solution without using hints which is pretty much identical to their solution
def sum_by_types(items: list[str, int]) -> tuple[str, int] | list[str, int]:
strtotal = "" # creating our variables with the values we'd want them to return if we don't have a value of that type
inttotal = 0
for i in items: # Iterating through the list
if type(i) == str: # if the item is a string
strtotal += i # add it to the end of our string
if type(i) == int: # if the item is an integer
inttotal += i # add to our sum of the integers
return [strtotal, inttotal] # return the string and the sum
# Bonus solution:
from functools import reduce # I had to look this up... I think reduce is similar to map in that is passes a function to
# all of the list elements, the difference being that you can have the elements interact (?)
def sum_by_types2(items: list[str, int]) -> tuple[str, int] | list[str, int]:
return reduce(lambda a, b: (a[0] + b, a[1]) # What I read online is that a, b can also kind of be read as:
if type(b) != int #"sum" (or working total), "current" (the item on the list)
else (a[0], a[1] + b), # so "a" is referring to the [('', 0)] list at the end
[('', 0)] + items) # so a[0] is referring to the string and a[1] is the integer
# so the first part is saying:
# return (the total string + new item, total integer)
# if the item is not an integer
# and the second part does the opposite
# returns (total string, total integer + new item)
# and it iterates like that through the whole list
# until you just return (string total, int total)
print("Example:")
print(list(sum_by_types(["1", "2", 3])))
assert list(sum_by_types([])) == ["", 0]
assert list(sum_by_types([1, 2, 3])) == ["", 6]
assert list(sum_by_types(["1", 2, 3])) == ["1", 5]
assert list(sum_by_types(["1", "2", 3])) == ["12", 3]
assert list(sum_by_types(["1", "2", "3"])) == ["123", 0]
assert list(sum_by_types(["size", 12, "in", 45, 0])) == ["sizein", 57]
print("The mission is done! Click 'Check Solution' to earn rewards!")
April 11, 2023
Comments: