Python中的无尽递归

时间:2010-02-18 03:03:57

标签: python recursion

完全披露,这是家庭作业的一部分(虽然是一个小片段,项目本身就是玩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

在深度为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

与此相互作用的功能(请注意,这接近于在此处发布的适当的边缘,我会在接受答案后删除此部分):[它原来并不是关键部分反正]]

2 个答案:

答案 0 :(得分:7)

你的代码:

class TreeNode:
    children = []

表示该类的每个实例共享相同的children列表。所以,在这一点:

def add_child(self, child):
    self.children.append(child)

你要附加到“class-global”列表。因此,当然,每个节点都是其他每个节点的子节点,并且可以保证灾难。

修复:将您的班级更改为

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 ...

其余部分不需要更改来修复此错误(虽然可能有机会改进它或修复其他错误,但我没有深入检查过),但未能在{{1}中分配self.children导致你当前的错误,并且没有继承__init__(除非你使用的是Python 3,但是如果是的话,我希望你能提及这个小细节;-)只是一个等待发生的错误。

答案 1 :(得分:3)

看起来self.children包含self

修改

对于children类的每个实例,TreeNode属性被初始化为同一个数组实例。

您需要为TreeNode添加self.children = [],为每个__init__实例创建一个单独的数组实例。
board数组存在同样的问题。