Advertisement
Advertisement


Getting the index of the returned max or min item using max()/min() on a list


Question

I'm using Python's max and min functions on lists for a minimax algorithm, and I need the index of the value returned by max() or min(). In other words, I need to know which move produced the max (at a first player's turn) or min (second player) value.

for i in range(9):
    newBoard = currentBoard.newBoardWithMove([i / 3, i % 3], player)

    if newBoard:
        temp = minMax(newBoard, depth + 1, not isMinLevel)  
        values.append(temp)

if isMinLevel:
    return min(values)
else:
    return max(values)

I need to be able to return the actual index of the min or max value, not just the value.

2018/10/12
1
488
10/12/2018 2:59:59 PM

Accepted Answer

if isMinLevel:
    return values.index(min(values))
else:
    return values.index(max(values))
2013/10/27
433
10/27/2013 8:10:51 PM


You can find the min/max index and value at the same time if you enumerate the items in the list, but perform min/max on the original values of the list. Like so:

import operator
min_index, min_value = min(enumerate(values), key=operator.itemgetter(1))
max_index, max_value = max(enumerate(values), key=operator.itemgetter(1))

This way the list will only be traversed once for min (or max).

2012/07/09

If you want to find the index of max within a list of numbers (which seems your case), then I suggest you use numpy:

import numpy as np
ind = np.argmax(mylist)
2012/11/23

Possibly a simpler solution would be to turn the array of values into an array of value,index-pairs, and take the max/min of that. This would give the largest/smallest index that has the max/min (i.e. pairs are compared by first comparing the first element, and then comparing the second element if the first ones are the same). Note that it's not necessary to actually create the array, because min/max allow generators as input.

values = [3,4,5]
(m,i) = max((v,i) for i,v in enumerate(values))
print (m,i) #(5, 2)
2013/10/19

list=[1.1412, 4.3453, 5.8709, 0.1314]
list.index(min(list))

Will give you first index of minimum.

2013/09/07

I think the best thing to do is convert the list to a numpy array and use this function :

a = np.array(list)
idx = np.argmax(a)
2019/01/05

Source: https://stackoverflow.com/questions/2474015
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]