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
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.
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.
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.
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.
Since Python 2.5 you can use max with a key parameter:
>>> max(a, key=sum)
[4, 5, 6]
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With