【发布时间】:2018-02-23 23:00:16
【问题描述】:
我尝试在 python 中编写一个极小极大算法。但这太令人困惑了。我是递归函数的新手。我的思维结构在某处有一些错误,但我无法解决。我的极小极大树返回“-100”,必须为 100 才能获得真正的答案。如果有任何遗漏或不清楚,请告诉我。谢谢
def startposition():
return 2, 'max'
def terminalstate(state):
if state == (0, 'min') or state == (0, 'max'):
return True
else:
return False
def minimax(state):
if terminalstate(state):
return utilitystatic(state)
else:
if state[1] == 'min':
value = -250
for x in successorsgenerator(state):
value = max(value, minimax(x))
elif state[1] == 'max':
value = 250
for x in successorsgenerator(state):
value = min(value, minimax(x))
return value
def utilitystatic(state):
assert terminalstate(state)
if state[1] == 'max':
return -100
elif state[1] == 'min':
return 100
assert False
def successorsgenerator(state):
successors = []
state = toggle(state)
newstate = decrease(state)
i = 0
while newstate[0] >= 0 and i < 3:
successors.append(newstate)
i += 1
newstate = decrease(newstate)
print('successors:', successors)
return successors
def toggle(state):
state = list(state)
state[1] = 'min' if state[1] == 'max' else 'max'
state = tuple(state)
return state
def decrease(state):
state = state[:0] + (state[0] - 1,) + state[1:2]
return state
stick = startposition()
exit = minimax(stick)
print('last result', exit)
【问题讨论】:
标签: python recursion tree minimax