完全披露,这是家庭作业的一部分(虽然一个小片段,项目本身就是玩AI的游戏).
我将此函数内置到树节点类中:
def recursive_score_calc(self):
current_score = self.board
for c in self.children:
child_score = c.recursive_score_calc()
if(turn_color == 1):
if(child_score > current_score):
current_score = child_score
else:
if(child_score < current_score):
current_score = child_score
self.recursive_score = current_score
return current_score
Run Code Online (Sandbox Code Playgroud)
在深度为1的树(一个根和一些子)上,它已经达到了Python递归限制.该函数旨在使用动态编程从下到上构建最小 - 最大树.说实话,我不知道为什么这不能按预期工作,但我对Python也很新.
Stack Overflow的好人:为什么这段代码会给我一个堆栈溢出?
有问题的整个班级:
from Numeric import *
class TreeNode:
children = []
numChildren = 0
board = zeros([8,8], Int)
turn_color = 0 # signifies NEXT to act
board_score = 0 # tally together board items
recursive_score = 0 # set when the recursive score function is called
def __init__(self, board, turn_color):
self.board = copy.deepcopy(board)
self.turn_color = turn_color
for x in range (0,7):
for y in range (0,7):
self.board_score = self.board_score + self.board[x][y]
def add_child(self, child):
self.children.append(child)
self.numChildren = self.numChildren + 1
def recursive_score_calc(self):
current_score = self.board # if no valid moves, we are the board. no move will make our score worse
for c in self.children:
child_score = c.recursive_score_calc()
if(turn_color == 1):
if(child_score > current_score):
current_score = child_score
else:
if(child_score < current_score):
current_score = child_score
self.recursive_score = current_score
return current_score
Run Code Online (Sandbox Code Playgroud)
与此相互作用的功能(请注意,这是接近适合发布的边缘,我接受答案后将删除此部分):[它不会成为关键部分]
这段代码:
class TreeNode:
children = []
Run Code Online (Sandbox Code Playgroud)
表示该类的每个实例共享相同的children列表.所以,在这一点:
def add_child(self, child):
self.children.append(child)
Run Code Online (Sandbox Code Playgroud)
你要附加到"类全局"列表.因此,当然,每个节点都是其他节点的子节点,并且可以保证灾难.
修复:将您的课程更改为
class TreeNode(object):
numChildren = 0
board = zeros([8,8], Int)
turn_color = 0 # signifies NEXT to act
board_score = 0 # tally together board items
recursive_score = 0 # set when the recursive score function is called
def __init__(self, board, turn_color):
self.children = []
self.board = copy.deepcopy(board)
self.turn_color = turn_color
... etc, etc ...
Run Code Online (Sandbox Code Playgroud)
其余的并不需要改变,以修复这个bug(虽然可能有机会改善其或修复其他错误,我没有检查它深深的),但未能分配self.children在__init__导致你目前的bug,并不能继承object(除非你使用的是Python 3,但我希望你能提一下这个小细节;-)只是一个等待发生的错误.