[Tutor] sumHighest function help
Peter Otten
__peter__ at web.de
Sat Nov 5 08:07:01 EDT 2016
Lloyd Francis wrote:
> I want to write a function that will calculate and return the sum of the
> *n* highest value in a list *a. *Also, when n is less than 0, the answer
> should be zero, and if n is greater than the number of elements in the
> list, all elements should be included in the sum.
>
> In addition i want to write the code in a function with only one line of
> code in it.
> So far I have:-
>
> def sumHighest(a, n):
> lambda a, n : sum(a[:n])
>
> This doesn't work but i want to use *lambda *and the slice in the
> function.
>
> An appropriate test would be:-
>
> input - sumHighest([1,2,3,4], 2)
> output - 7
>
> thanks L.
sum_highest = lambda items, n: sum(sorted(items, reverse=True)[:max(n, 0)])
or better:
import heapq
def sum_highest(items, n):
return sum(heapq.nlargest(n, items))
More information about the Tutor
mailing list