Search code examples
pythonminimax

Minimax python - how to efficiently find alternating max and mins in a tree


The following code I'm using to minimax a tree looks awful. Surely there is a way to simplify this and use a function instead of a int.MaxValue

if depth%2==1:
    min = 9999
    for child in currentRoot.children:
        if child.score < min:
            min = child.score
    currentRoot.score = min
else:
    max = -9999
    for child in currentRoot.children:
        if child.score > max:
            max = child.score
    currentRoot.score = max
return currentRoot.score

Solution

  • First, don't use min and max for variable names as this shadows the built-in functions. Second, use these built-in functions!

    You can use your current logic to pick out whether you want min or max and then pass a generator expression to access each child's score.

    measure = min if depth % 2 else max
    return measure(c.score for c in currentRoot.children)