Luke_Smith_Lukasaurus
Luke_Smith_Lukasaurus

Reputation: 59

Find maximum value of minimum elements in tuple

If I have a list

[[209, 34], [50, 170], [197, 32], [75, 156], [176, 51], [54, 141], [205, 19], [35, 173]]

How would I go about finding the sublist with the maximum minimum element?

ie, in the case above, it would be index[3] - [75,156] because it's minimum value is greater than the minimum value of all other elements.

Upvotes: 1

Views: 1312

Answers (2)

Kei Minagawa
Kei Minagawa

Reputation: 4521

You can use sorted function.

>>> lst = [[209, 34], [50, 170], [197, 32], [75, 156], [176, 51], [54, 141], [205, 19], [35, 173]]
[[209, 34], [50, 170], [197, 32], [75, 156], [176, 51], [54, 141], [205, 19], [35, 173]]
>>> sorted(lst, key=min, reverse=True)
[[75, 156],
 [54, 141],
 [176, 51],
 [50, 170],
 [35, 173],
 [209, 34],
 [197, 32],
 [205, 19]]

key=min means it will use min function when sorting the list.

Then you can find the index of the value with index method. Like:

>>> lst.index([75, 156])
3

Upvotes: 0

mgilson
mgilson

Reputation: 310049

It should be as simple as:

max(list_of_iterables, key=min)

i.e.:

>>> lst = [[209, 34], [50, 170], [197, 32], [75, 156], [176, 51], [54, 141], [205, 19], [35, 173]]
[[209, 34], [50, 170], [197, 32], [75, 156], [176, 51], [54, 141], [205, 19], [35, 173]]
>>> max(lst, key=min)
[75, 156]

The max (and min) functions work by walking through an iterable and comparing each element in the iterable picking out the biggest (or smallest for min) element. The catch is that the thing compared is the result of the key function applied to the individual element. By default, the key function is just the identity function -- but it can be anything you want. In this case, my key function is min which picks out the minimum value of the sub-list. We then compare the sublists based on their minimum value and pick out the max which is exactly what your question asked for.

Upvotes: 6

Related Questions