Ad
  • Custom User Avatar
  • Default User Avatar

    Good one. I will try to remember that code to future tasks

  • Default User Avatar

    sum takes an iterable as its primary argument and sums all the values in that iterable. This can be a list or array-like structure, but here we see it can also be a generator comprehension, which is a clause of the form expr for vars in source [if condition]. The generator comprehension iterates through the source, expanding each element into the one or more variables of vars, testing if the optional if expression is true, and then if so, yielding the results of evaluating expr. You can think of a generator as an internal function of its own that can return multiple values, generated one at a time. Later, you might learn how to use the yield keyword to do the same with any function. But until then, remember calling return always ends the function and returns a value. That means if you put it inside of a loop, it will abort that loop and end the function right then. Sometimes that can be handy, but not here. You want to loop through every value in arr, and a comprehension will do that.

  • Default User Avatar

    This comment is hidden because it contains spoiler information about the solution

  • Custom User Avatar

    Acording to my peformance tests the one with sum and map is most time efficient, i was not expecting it to be so comparing to pure loops, but i guess we are better off using built-in functions?

    PS: i had solved it like this as well...

  • Default User Avatar

    I solved it like this as well -- is this the most time- and space-efficient solution?