[英]How to properly implement trees with n-branching factor in python?
我正在嘗試在python中實現minimax算法,但是在創建分支樹結構時遇到了一些問題。 我仍然是一名業余程序員,所以請不要介意我的代碼是否不好。 這是我的節點結構
class Node:
parent = None
state = None
pmax = 0 #this represents the MAX player symbol; i.e. SELF
pmin = 0 #this represents the MIN player symbol; i.e. OPPONENT
stateCost = 0 #this represents utility cost of leaf nodes based on the matrix state
bestCost = None #this represents the chosen path in the minimax algorithm
children = []
def __init__(self,mat,up,mx,mn):
self.parent = up
self.state = mat
self.pmax = mx
self.pmin = mn
stateCost = 0
def addChild(self,newState,up):
n = Node(newState,up,self.pmax,self.pmin)
self.children.append(n)
def evaluateChildren(self,minmax):
ln = len(self.state[0])
for x in range(ln):
#newState = insertIntoSink(self.state[0],x)
cloneState = cloneMatrix(self.state)
newState = insertIntoSink(cloneState,x,minmax)
print "state being added"
for list in newState:
print list
self.addChild(newState,self)
print "done Evaluating CHILDREN"
def evaluateSubChildren(self,minimax):
ln = len(self.state[0])
for l in self.children:
for x in range(ln):
cloneState = cloneMatrix(self.state)
newState = insertIntoSink(cloneState,x,minimax)
l.addChild(newState,l)
在我正在做的情況下,根節點必須有7個子代,每個子代本身應有7個子代。 每個子節點將在父節點中具有初始矩陣的修改克隆。
發生的錯誤是,在添加子子級(即第二級子級)之后,未將其添加到子級列表中,而是將其添加到了根節點中。
創建孩子的過程如下。
def getBestMove(self):
move =0
maxVal = -1;
i=-1;
#evaluate all the 7 children
self.evaluateChildren(2)
self.evaluateSubChildren(1)
#more calculations go here
我首先嘗試調用以下相同的validateChildren()函數:
def getBestMove(self):
move =0
maxVal = -1;
i=-1;
#evaluate all the 7 children
self.evaluateChildren(2)
#evaluate second level children
for n in self.children:
print "evaluating SECOND LEVEL CHILDREN"
n.evaluateChildren()
如果我在評估后檢查根節點的子代數,則應該為7,但它會繼續向其添加更多的2級子代,這將使我的程序陷入無限循環。
請讓我知道我要去哪里了。 請詢問是否需要更多信息。
您正在使用Python中的列表和變量綁定達到常見的目的-使children = []
成為類變量,這使它在每個Node中都是相同的列表 。 內存中只有一個列表,每個節點都指向它。 更改它,所有節點都將看到更改。 將其移到__init__
以使其成為每個實例的新實例。
Class Node:
def __init__(self,mat,up,mx,mn):
self.children = []
各種各樣的人都在討論相同的問題,“很多東西錯誤地引用了完全相同的列表”,有關發生的事情,原因,如何避免的討論很多:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.