Skip to content Skip to sidebar Skip to footer

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 fo

Solution 1:

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)

Solution 2:

def findNewScore(isEven):
    if isEven:
        root.score = max([c.score for c in root.children] + [-999])
    else:
        root.score = min([c.score for c in root.children] + [999])
    return root.score

Or even just:

def findNewScore(isEven):
    s = sorted(c.score for score in root.children)
    if isEven:
        root.score = max([-999, s[-1]])
    else:
        root.score = min([999, s[0]])
    return root.score

Post a Comment for "Minimax Python - How To Efficiently Find Alternating Max And Mins In A Tree"