0

I've been working on a function that takes a two dimensional list of nums as a parameter and returns a list with the index of the row with the highest sum of values and the sum of those values. This is as far as i've gotten. I've tried accumulator, if [i]+1>i: but keep getting error message can only concanetate list not int. I've tried adding for j in newList: and too many nums print out.Can someone help me out. 1st year programmer and really stuck. When I use max error not iterable.

def FindLargestRow(lsts):
    newList=[]
    for i in lsts:
    newList.append(sum(i))
    return newList

print(FindLargestRow([[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]]))
print()

desired result is:

Start FindLargestRow [1,15]

2
  • 1
    show the desired result Commented May 15, 2017 at 17:23
  • Can you fix the formatting in your code's markdown and also include the traceback of the error? Commented May 15, 2017 at 17:24

5 Answers 5

1

You can use the max and index functions:

 maxList = max(newList)
 return newList.index(maxList), maxList
Sign up to request clarification or add additional context in comments.

Comments

1

You can map sum() to the list and find the max sum. With that index, you can find the index of the list that has the maximum sum.

def FindLargestRow(lsts):
    s=map(sum,lsts)
    return s.index(max(s)),max(s)

That is,

>>> d=[[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]]
>>> map(sum,d)
[6, 15, 3, 10]
>>> s=map(sum,d)
>>> s
[6, 15, 3, 10]
>>> max(s)
15
>>> s.index(max(s))
1
>>> d[s.index(max(s))]
[1, 2, 3, 4, 5]

1 Comment

This really helped. I didn't know about map yet so I'm still reading up on it. Ran through python tutor and it was much shorter than the other way I did it. Will post. Thanks
1

Try the following, which uses a 2D array to keep a track of the highest sum:

def FindLargestRow(lsts):
    lengths = []
    for i in lsts:
        lengths.append([i, sum(i)])
    return max(lengths, key=lambda x:x[1])[0] 

>>> print(FindLargestRow([[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]]))
[1, 2, 3, 4, 5]

1 Comment

I tried to put the lambda code in python tutor to understand how it worked. Going to have to run a couple more times thanks. I did figure out a different way.
0

You can try this:

the_list = [[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]]

new_list = map(sum, the_list)


return [[i for i in range(len(the_list)) if sum(the_list[i]) == max(new_list)][0], max(new_list)]

Comments

-1
def FindLargestRow(lsts):   
    largestSize=0
    largestRow=0


    for i in range(0,len(lsts)):


       if sum(lsts[i])>=largestSize:



           largestRow = i

           largestSize = sum(lsts[i])

return [largestRow,largestSize]

print(FindLargestRow([[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]])) print()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.