Minimax python - 如何有效地在树中找到交替的最大值和最小值
Minimax python - how to efficiently find alternating max and mins in a tree
我用来最小化一棵树的以下代码看起来很糟糕。当然有一种方法可以简化它并使用函数而不是 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
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
甚至只是:
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
首先,不要使用 min
和 max
作为变量名,因为这会遮蔽 built-in 函数。其次,使用这些 built-in 功能!
您可以使用当前的逻辑来选择您想要 min
还是 max
,然后传递一个生成器表达式来访问每个 child 的分数。
measure = min if depth % 2 else max
return measure(c.score for c in currentRoot.children)
我用来最小化一棵树的以下代码看起来很糟糕。当然有一种方法可以简化它并使用函数而不是 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
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
甚至只是:
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
首先,不要使用 min
和 max
作为变量名,因为这会遮蔽 built-in 函数。其次,使用这些 built-in 功能!
您可以使用当前的逻辑来选择您想要 min
还是 max
,然后传递一个生成器表达式来访问每个 child 的分数。
measure = min if depth % 2 else max
return measure(c.score for c in currentRoot.children)