Python 执行时间问题

0 投票
1 回答
644 浏览
提问于 2025-04-16 01:26

我能顺利执行第一个函数……但是第二个函数没有运行……就是 getaction。

 def registerInitialState(self, state):
    """
    This is the first time that the agent sees the layout of the game board. Here, we
    choose a path to the goal.  In this phase, the agent should compute the path to the
    goal and store it in a local variable.  All of the work is done in this method!

    state: a GameState object (pacman.py)
    """
    if self.searchFunction == None: raise Exception, "No search function provided for SearchAgent"
    starttime = time.time()
    problem = self.searchType(state) # Makes a new search problem
    self.actions  = self.searchFunction(problem) # Find a path
    totalCost = problem.getCostOfActions(self.actions)
    print('Path found with total cost of %d in %.1f seconds' % (totalCost, time.time() - starttime))
    if '_expanded' in dir(problem): print('Search nodes expanded: %d' % problem._expanded)

  def getAction(self, state):
    """
    Returns the next action in the path chosen earlier (in registerInitialState).  Return
    Directions.STOP if there is no further action to take.

    state: a GameState object (pacman.py)
    """
    if 'actionIndex' not in dir(self): self.actionIndex = 0
    i = self.actionIndex
    self.actionIndex += 1
    if i < len(self.actions):
      return self.actions[i]    
    else:
      return Directions.STOP


Error:  File  line 114, in getAction
    if i < len(self.actions):
TypeError: len() of unsized object

这是我的函数:当我执行的时候,它应该给我节点的值,但实际上却给了我一个错误。在 get action 函数中,i 的值是 0。我不知道为什么它没有增加。

while stack.isEmpty()!= 0:  
        node = stack.pop()
        print node

错误:

(5, 5)
Path found with total cost of 999999 in 0.0 seconds
Search nodes expanded: 1
None

1 个回答

1

在下面加上打印语句,然后告诉我打印出来的内容是什么。self.actions 可能是 None 类型,或者不是一个像列表那样的对象。你可能需要像其他地方那样检查一下是否等于 None。

self.actionIndex += 1 
print self.actions
if i < len(self.actions): 
  return self.actions[i]     
else: 
  return Directions.STOP 

所以问题可能出在这里:

problem = self.searchType(state) # Makes a new search problem 
self.actions  = self.searchFunction(problem) # Find a path 

让 self.actions 等于 None

你可以进一步调试:

problem = self.searchType(state) # Makes a new search problem 
print problem
self.actions  = self.searchFunction(problem) # Find a path 

检查问题是否存在……如果存在,searchFunction 可能没有找到路径,或者出现了其他问题,导致它返回了 None。

撰写回答