tags:

views:

147

answers:

2

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.

+1  A: 
if isMinLevel:
    return values.index(min(values))
else:
    return values.index(max(values))

Edit: Removed alternate solution that didn't work

too much php
That does it! Thanks.
Kevin Griffin
@KevinGriffin, Note that this gets you only one of possibly several occurrences of the minimum/maximum. This may not be what you want, for example if it's possible to increase your gain the same two ways, but one of them hurts the other player more. I do not know if this is a case you need to consider.
Mike Graham
+4  A: 

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:

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).

Matt Anderson