Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Finding the last index of min element?

Tags:

python

list

min

For example [1,2,3,4,1,2]

has min element 1, but it occurs for the last time at index 4.

like image 673
John Smith Avatar asked Jul 30 '13 16:07

John Smith


3 Answers

>>> values = [1,2,3,4,1,2]
>>> -min((x, -i) for i, x in enumerate(values))[1]
4

No modification to the original list, works for arbitrary iterables, and only requires one pass.

This creates an iterable of tuples with the first value being the original element from the list, and the second element being the negated index. When finding the minimum in this iterable of tuples the values will be compared first and then the indices, so you will end up with a tuple of (min_value, lowest_negative_index). By taking the second element from this tuple and negating it again, you get the highest index of the minimum value.

Here is an alternative version that is very similar, but uses a key function for min():

>>> min(range(len(values)), key=lambda i: (values[i], -i))
4

Note that this version will only work for sequences (lists, tuples, strings etc.).

like image 150
Andrew Clark Avatar answered Sep 20 '22 23:09

Andrew Clark


a = [1,2,3,4,1,2]

a.reverse()
print len(a) - a.index(min(a)) - 1

Update after comment:

The side effect can be removed by reversing again (but of course that is quite inefficient).

a.reverse()
like image 42
Michel Keijzers Avatar answered Sep 22 '22 23:09

Michel Keijzers


len(list_) - list_[::-1].index(min(list_)) - 1

Get the length of the list, subtract from that the index of the min of the list in the reversed list, and then subtract 1.

like image 34
rlms Avatar answered Sep 20 '22 23:09

rlms