tibetish
tibetish

Reputation: 119

Maximum sum of sub list in a list of lists

Making my first steps in Python. I have a list of lists and i'm trying to return the sub list with largest sum of all sub lists. For now I just have the max sum itself. Ex: this code returns 18, but I need to return [3,3,3,3,3,3]

Any directions? Thanks

def find_biggest(lst):
    inner_list_sum = []
    for i in range(len(lst)):
        inner_list_sum.append(sum(lst[i]))    # list of elements sums
    return max(inner_list_sum)                # I actually need the element itself...not the max sum

print(find_biggest([[1,2,3,4], [1,2,3,3], [1,1], [3,3,3,3,3,3]]))

Upvotes: 2

Views: 669

Answers (3)

Gaurav Agarwal Garg
Gaurav Agarwal Garg

Reputation: 113

import functools

def find_biggest(lst):
    return functools.reduce(lambda x, y : x if sum(x) > sum(y) else y, lst)

Here, the used lambda expression is the function equivalent to find the greatest sum and lst is iterable.

Please note: reduce will directly work for python2, you need to import functools
for python3only.

Using functools.reduce

Upvotes: 0

tibetish
tibetish

Reputation: 119

OK Since I'm not allowed to use (max(data, key=sum)). I did this not very elegant code, but it was accepted a correct answer

def find_biggest(lst):
    inner_list_sum = []
    for i in range(len(lst)):
        inner_list_sum.append(sum(lst[i]))    # list of elements sums
        max_element=max(inner_list_sum)
        seq_index= inner_lis

Upvotes: 0

Rakesh
Rakesh

Reputation: 82785

Use max with key=sum

Ex:

data = [[1,2,3,4], [1,2,3,3], [1,1], [3,3,3,3,3,3]]
print(max(data, key=sum))

Output:

[3, 3, 3, 3, 3, 3]

Upvotes: 6

Related Questions