[英]When returning a value from a function in python, it comes back empty
我正在為一個簡單的棋盤游戲制作一個 minmax 算法。 當 findparent function 返回數據時,有時工作正常,有時由於某種原因返回為空。 請幫忙。 以下是代碼的故障部分。
from sys import maxsize
class Node(object):
def __init__(self,idepth,iplayernum,iboard):
self.idepth=idepth
self.iplayernum=iplayernum
self.iboard=iboard
self.children=[]
self.createchildren()
def createchildren(self):
if self.idepth>=0:
for x in range(0,4):
if self.iboard[x]>0:
for y in range(1,self.iboard[x]+1):
xiboard=self.iboard.copy()
xiboard[x]-=y
self.children.append(Node(self.idepth-1,-self.iplayernum,xiboard))
def checknodes(node,turn,ibestvalue,bestchoice):
for n in range(len(node.children)):
nchild=node.children[n]
childarr=[nchild,nchild.iboard]
for z in range(0,(idepth-nchild.idepth)):
childarr=findparent(childarr[0],inode)
print(childarr,'after return')
bestchoice=childarr[1]
if nchild.idepth>0:
checknodes(nchild,turn*-1,ibestvalue,bestchoice)
return(bestchoice)
def findparent(fnode,node):
for n in range(len(node.children)):
nhild=node.children[n]
if nhild==fnode and nhild.iboard==fnode.iboard:
print([node,node.iboard],'before return')
return [node,node.iboard]
elif nhild.idepth>0:
findparent(fnode,nhild)
iboardstart=[7,5,3,1]
idepth=3
icurplayer=1
row=int(input('The board is\n{}\n{}\n{}\n{}\nWhat row would you like to take from?'.format(iboardstart[0],iboardstart[1],iboardstart[2],iboardstart[3])))-1
amount=int(input('\nHow many would you like to take?'))
iboardstart[row]-=amount
icurplayer*=-1
inode=Node(idepth,icurplayer,iboardstart)
bestchoice=-100
ibestvalue=-icurplayer*maxsize
bestchoice=checknodes(inode,-1,ibestvalue,bestchoice)
iboardstart=bestchoice
print('Computer plays\n{}\n{}\n{}\n{}'.format(iboardstart[0],iboardstart[1],iboardstart[2],iboardstart[3]))
icurplayer*=-1
如果您運行它,只需輸入 1 代表行和 1 代表金額,然后查看它打印出來的內容。 希望你們能幫助我,我將不勝感激。
您的問題是findparent
實際上並沒有從其遞歸調用中返回任何內容。 但是它不像return findparent(fnode,nhild)
那樣簡單,因為如果它在錯誤的分支中搜索,它有可能返回None
。 因此,您需要從遞歸調用中獲取值,檢查該值是否存在,如果存在則返回它。
你可以嘗試這樣的事情:
def findparent(fnode, node):
value = None
for nchild in node.children:
if nchild is fnode and nchild.iboard == fnode.iboard:
print([node, node.iboard], 'before return')
value = [node, node.iboard]
elif nchild.idepth > 0:
value = findparent(fnode, nchild)
if value:
return value
作為旁注,當循環遍歷列表的元素時,最好使用
for nchild in node.children:
代替
for n in range(len(node.children)):
nchild=node.children[n]
checknodes
方法中似乎有一個錯字:
嘗試改變
childarr=findparent(childarr[0],inode)
進入
childarr=findparent(childarr[0],node)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.