【问题标题】:Not being passed desired value for python tree没有被传递给 python 树的期望值
【发布时间】:2016-06-15 03:43:55
【问题描述】:

我找不到可以用来为国际象棋开局创建树结构的 python 树,所以我尝试自己编写。为了深入到树中,我尝试在添加新位置时返回子根,但似乎所有位置都被添加到根中,并且没有像我预期的那样获得对子根的引用,尽管我做了检查,root也有很多孙子。

import chess.pgn

class Node(object):
    children = []
    score = None
    def __init__(self, fen):
        self.fen = fen  
    def add(self, fen):
        for c in self.children:
            if c.fen == (fen):
                print("working")
                return c
        self.children.append(Node(fen))
        return self.children[-1]

root = Node('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1')
def createTree(fileName):
    pgn = open(fileName)
    game = chess.pgn.read_game(pgn)
    while(game):    
        next_move = game.variations[0]
        fen = next_move.board().fen()
        global root
        currentRoot = root.add(fen)

        while(not next_move.is_end() and next_move.board().fullmove_number <= 5):
            next_move = next_move.variations[0]
            fen = next_move.board().fen()
            currentRoot = currentRoot.add(fen)
            print(currentRoot.children)
        game = chess.pgn.read_game(pgn)

file = r"C:\all.pgn"
createTree(file)
for n in root.children:
    print(n.fen)

【问题讨论】:

标签: python tree parameter-passing pass-by-reference chess


【解决方案1】:

您的代码失败是因为您误用了class variables.

基本上,当您在任何函数之外声明 children 时,它的作用域是类级别的,并且所有 Node 对象共享同一个列表。您希望在 __init__ 中将其定义为 self.children,以便在实例级别进行范围限定。

class Node:
    def __init__(self, fen):
        self.fen = fen
        self.score = None
        self.children = []
    ...

【讨论】:

  • 这是有道理的。希望它能解决它!
  • @Josh 请记住,如果代码对您有用,请选择它作为接受的答案。谢谢!
  • 它确实修复了它。而且我还能够制作一些递归方法来遍历它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-29
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 2017-06-20
相关资源
最近更新 更多