Home > Software design >  How to find the maximum of two lists at the same indices
How to find the maximum of two lists at the same indices

Time:11-17

I am trying to find the maximum point for two different lists at the same index. Example:

l1 = [11,4,7,9]
l2 = [2,10,9,6]

The result from this example would be that l1 and l2 are both maximized at their third index (where l1 = 7 and l2 = 9).

Is there an existing function that can do this? If not, how would I approach this.

CodePudding user response:

You could write a simple argmax function (as given in this answer):

def argmax(iterable):
    return max(enumerate(iterable), key=lambda x: x[1])[0]

And call it on the pairwise sums:

argmax(map(sum, zip(l1, l2)))
# 2

Some docs on the utils:

CodePudding user response:

You really need to better define what you mean/expect as the "both maximized" concept.

For example, the pairs of values could be treated as x,y coordinates in a cartesian plane with the farthest euclidian distance from origin representing the maximized concept:

l1 = [11,4,7,9]
l2 = [2,10,9,6]

i = max(range(len(l1)),key=lambda i:l1[i]**2 l2[i]**2)
print(i)
2

This selects the 3rd index but so would the simple sum of values in this particular case.

  • Related