[Tutor] sumHighest function help

Alan Gauld alan.gauld at yahoo.co.uk
Sat Nov 5 08:42:06 EDT 2016


On 05/11/16 12:07, Peter Otten wrote:

> 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))

No, the first solution is "better" because it used lambda
and slicing and so meets all of the OP's "requirements" ;-)


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list