1

I need an index of the element with the max sum inside of it, but what I done is only found the maximun inside the tuple in a listm instead of fining the index. Could you please help.

def max_sum_index(tuples):  
   
    # YOUR CODE HERE
    maxi = 0
  
    # traversal in the lists 
    for x in tuples: 
        sum = 0 
        # traversal in tuples in list 
        for y in x: 
            sum+= y      
        maxi = max(sum, maxi)  
          
    return maxi

print(max_sum_index([(10, 20), (40, 32), (30, 25)]))
#72

4 Answers 4

2

to keep track of indices you may want to use enumerate

for i,x in enumerate(tuples):

then to keep track of index you need a variable for the highest sum and the index of that sum:

maxi = 0
max_val = 0

If you find an element that has a sum higher than max_val then that becomes the new max, along with it's index

    if sum > max_val:
        max_val = sum
        maxi = i 

So you'd have something like:

def max_sum_index(tuples):  
   
    maxi = 0
    max_val = 0
  
    # traversal in the lists 
    for i,x in enumerate(tuples): 
        sum = 0 
        # traversal in tuples in list 
        for y in x: 
            sum+= y
        if sum > max_val:
            max_val = sum
            maxi = i 
          
    return maxi

print(max_sum_index([(10, 20), (40, 32), (30, 25)]))
Sign up to request clarification or add additional context in comments.

Comments

2
sample = [(10, 20), (40, 32), (30, 25)]

index = sample.index(max(sample, key=sum))
print(index)

Output: 1

1 Comment

Or just key=sum. I don't see the benefit of lambda x:sum(x).
1

uses a tuple with sum as first element to get maximum and include original tuple
index is the second element of the tuple, original tuple is the third element:

print(max((sum(x),i,x) for i,x in enumerate([(10, 20), (40, 32), (30, 25)])))
print('index: ', max((sum(x),i,x) for i,x in enumerate([(10, 20), (40, 32), (30, 25)]))[1])

Comments

0

You can use the list max function over your tuple.

max_index = max(enumerate([(10, 20), (40, 32), (30, 25)]), 
                key=lambda x: x[1][0]+x[1][1])[0]

print(max_index) #outputs 1 in this case

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.