Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding maximum of a list of lists by sum of elements in Python

What's the idiomatic way to do maximumBy (higher order function taking a comparison function for the test), on a list of lists, where the comparison we want to make is the sum of the list, in Python?

Here's a Haskell implementation and example output:

> maximumBy (compare `on` sum) [[1,2,3],[4,5,6],[1,3,5]]
> [4,5,6]

And implementations of those base library functions, just for completeness (in case you want to use reduce or something :)

maximumBy cmp xs =  foldl1 maxBy xs
    where
       maxBy x y = case cmp x y of GT -> x; _ -> y

k `on` f = \x y -> f x `k` f y

sum      =  foldl' (+) 0
like image 419
Don Stewart Avatar asked May 04 '10 05:05

Don Stewart


People also ask

How do you find the maximum of a sum in Python?

The above syntax of max() function allows us to find the sum of list in list using the key=sum. max(list1, key=sum), this finds the list with maximum sum of elements and then sum(max(list1, key=sum)) returns us the sum of that list.

How do you find the maximum number of a list in Python?

In Python, there is a built-in function max() you can use to find the largest number in a list. To use it, call the max() on a list of numbers. It then returns the greatest number in that list.

How do you sum a list of elements in Python?

Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.

Can you sum two lists in Python?

The sum() function is used to add two lists using the index number of the list elements grouped by the zip() function. A zip() function is used in the sum() function to group list elements using index-wise lists.


2 Answers

Since Python 2.5 you can use max with a key parameter:

>>> max(a, key=sum)
[4, 5, 6]
like image 80
Mark Byers Avatar answered Sep 27 '22 20:09

Mark Byers


It isn't terribly efficient, but:

reduce(lambda x,y: x if sum(x)>sum(y) else y, [[1,2,3],[4,5,6],[1,3,5]])
like image 30
outis Avatar answered Sep 27 '22 21:09

outis