Python:Name not defined错误,即使函数在调用前已明确定义
我是python新手,对函数定义有一个奇怪的问题。我已经检查了论坛,并确保在调用之前定义了我的函数,但是这对问题没有帮助。在这个特定的方法中,当我尝试按字面意义调用函数时,我不断得到一个名称未定义的错误Python:Name not defined错误,即使函数在调用前已明确定义,python,python-3.x,function,compiler-errors,Python,Python 3.x,Function,Compiler Errors,我是python新手,对函数定义有一个奇怪的问题。我已经检查了论坛,并确保在调用之前定义了我的函数,但是这对问题没有帮助。在这个特定的方法中,当我尝试按字面意义调用函数时,我不断得到一个名称未定义的错误 from eight_puzzle import Puzzle import math ################################################################ ### Node class and helper functions p
from eight_puzzle import Puzzle
import math
################################################################
### Node class and helper functions provided for your convience.
### DO NOT EDIT!
################################################################
class Node:
"""
A class representing a node.
- 'state' holds the state of the node.
- 'parent' points to the node's parent.
- 'action' is the action taken by the parent to produce this node.
- 'path_cost' is the cost of the path from the root to this node.
"""
def __init__(self, state, parent, action, path_cost):
self.state = state
self.parent = parent
self.action = action
self.path_cost = path_cost
def gen_child(self, problem, action):
"""
Returns the child node resulting from applying 'action' to this node.
"""
return Node(state=problem.transitions(self.state, action),
parent=self,
action=action,
path_cost=self.path_cost + problem.step_cost(self.state, action))
@property
def state_hashed(self):
"""
Produces a hashed representation of the node's state for easy
lookup in a python 'set'.
"""
return hash(str(self.state))
################################################################
### Node class and helper functions provided for your convience.
### DO NOT EDIT!
################################################################
def retrieve_solution(node,num_explored,num_generated):
"""
Returns the list of actions and the list of states on the
path to the given goal_state node. Also returns the number
of nodes explored and generated.
"""
actions = []
states = []
while node.parent is not None:
actions += [node.action]
states += [node.state]
node = node.parent
states += [node.state]
return actions[::-1], states[::-1], num_explored, num_generated
################################################################
### Node class and helper functions provided for your convience.
### DO NOT EDIT!
################################################################
def print_solution(solution):
"""
Prints out the path from the initial state to the goal given
a tuple of (actions,states) corresponding to the solution.
"""
actions, states, num_explored, num_generated = solution
print('Start')
for step in range(len(actions)):
print(puzzle.board_str(states[step]))
print()
print(actions[step])
print()
print('Goal')
print(puzzle.board_str(states[-1]))
print()
print('Number of steps: {:d}'.format(len(actions)))
print('Nodes explored: {:d}'.format(num_explored))
print('Nodes generated: {:d}'.format(num_generated))
################################################################
### Skeleton code for your Astar implementation. Fill in here.
################################################################
class Astar:
"""
A* search.
- 'problem' is a Puzzle instance.
"""
def __init__(self, problem):
self.problem = problem
self.init_state = problem.init_state
self.num_explored = 0
self.num_generated = 1
def selectState(self, listOfStates):
'''
Selects the loweset cost node for expansion based on f(n) = g(n) + h(n)
'''
lowestCostPath = listOfStates[0].path_cost
index = int(1)
lowestNodeIndex = int(0)
while index != len(listOfStates):
scannedPathCost = listOfStates[index].path_cost
if index < scannedPathCost:
lowestCostPath = scannedPathCost
lowestNodeIndex = index
index += 1
return listOfStates[lowestNodeIndex]
def f(self,node, method):
'''
Returns a lower bound estimate on the cost from root through node
to the goal.
'''
return node.path_cost + self.h(node, method)
def getManhattanDistance(self, node):
'''
Evaluates the manhattan distance for a given state
'''
iterator = int(0)
misplacedCount = int(0)
totalDistance = int(0)
while iterator != len(node.state):
if iterator != node.state[iterator] and node.state[iterator] != 0:
misplacedCount = misplacedCount + 1
xCurrent = int(node.state[iterator]/3)
yCurrent = int(node.state[iterator]%3)
xDesired = int(iterator/3)
yDesired = int(iterator%3)
totalDistance = totalDistance + int(abs(xCurrent - xDesired)) + int(abs(yCurrent - yDesired))
iterator = iterator + 1
return totalDistance + misplacedCount
def h(self,node, method='man'):
'''
Returns a lower bound estimate on the cost from node to the goal
using the different heuristics.
'''
################################################################
### Your code here.
################################################################
if method == 'man':
self.getManhattanDistance(node)
return -1
elif method == 'rowcol':
return -1 # compute rowcol heuristic
elif method == 'misplaced':
return -1 # compute misplaced tiles the number of tiles out of place
elif method == 'null':
return -1 # compute null heuristic
else:
return 0
def method_stats(self, board, trials=100, method='man'):
'''
Returns an mean and standard deviation of the number of nodes expanded
'''
# write code here to randomly generate puzzles and
# compute the mean and standard deviation of the number
# nodes expanded. You can use np.mean() and np.std()
expanded_mean = 0.
expanded_std = 0.
for t in range(trials):
puzzle = Puzzle(board).shuffle()
solver = Astar(puzzle)
actions, states, num_explored, num_generated = solver.solve(method=method)
############################################################
### Compute upper bound for branching factor and update b_hi
### Your code here.
############################################################
return expanded_mean, expanded_std
def anotherFunction(self, node, method):
return 1
def generateStatesFor(self, node, method, listOfStates):
'''
Decides how to select an action from a list of available actions
'''
def solve(self, method='man'):
node = Node(state = self.init_state,
parent = None,
action = None,
path_cost = 0)
num_explored = int(0)
num_generated = int(0)
listOfStates = []
listOfStates.append(node)
print(listOfStates[0].state)
anotherFunction(self, node, method)
return retrieve_solution(node, num_explored=num_explored, num_generated=num_generated)
if __name__ == '__main__':
# Simple puzzle test
## board = [[3,1,2],
## [4,0,5],
## [6,7,8]]
board = [[7,2,4],
[5,0,6],
[8,3,1]]
puzzle = Puzzle(board)
solver = Astar(puzzle)
solution = solver.solve()
##print_solution(solution)
# Harder puzzle test
board = [[7,2,4],
[5,0,6],
[8,3,1]]
puzzle = Puzzle(board)
solver = Astar(puzzle)
##solution = solver.solve()
##print(len(solution[0]))
# branching factor test
method='man'
emean, estd = solver.method_stats(board, trials=100, method=method)
##print('mean and standard deviation: {0:.2f}, {1:.2f} using heuristic: {2}'.format(emean, estd, method))
从八个拼图导入拼图
输入数学
################################################################
###为方便起见,提供了节点类和助手函数。
###不要编辑!
################################################################
类节点:
"""
表示节点的类。
-“状态”保存节点的状态。
-“父节点”指向节点的父节点。
-“action”是父节点为生成此节点而采取的操作。
-“path_cost”是从根节点到此节点的路径的成本。
"""
定义初始化(自身、状态、父级、操作、路径成本):
self.state=状态
self.parent=parent
行动
self.path\u cost=路径成本
def gen_儿童(自身、问题、行动):
"""
返回将“操作”应用到此节点所产生的子节点。
"""
返回节点(状态=问题.transitions(self.state,action),
父母=自己,
行动,
路径成本=self.path成本+问题。步骤成本(self.state,action))
@财产
def状态_散列(自):
"""
生成节点状态的哈希表示,以便于
在python“集合”中查找。
"""
返回散列(str(self.state))
################################################################
###为方便起见,提供了节点类和助手函数。
###不要编辑!
################################################################
def检索解决方案(节点、已探索的数量、已生成的数量):
"""
返回上的操作列表和状态列表
给定目标状态节点的路径。还返回数字
探索和生成的节点数。
"""
动作=[]
国家=[]
当node.parent不是None时:
操作+=[节点.操作]
状态+=[节点状态]
node=node.parent
状态+=[节点状态]
返回操作[::-1],状态[::-1],已探索的数量,已生成的数量
################################################################
###为方便起见,提供了节点类和助手函数。
###不要编辑!
################################################################
def打印溶液(溶液):
"""
打印出从初始状态到给定目标的路径
对应于解决方案的(操作、状态)元组。
"""
操作、状态、探索的数量、生成的数量=解决方案
打印('开始')
对于步进范围(len(动作)):
打印(拼图板_str(状态[步骤])
打印()
打印(操作[步骤])
打印()
打印('目标')
打印(拼图板(状态[-1]))
打印()
打印('步骤数:{:d}'。格式(len(actions)))
打印('已探索的节点:{:d}'。格式(已探索的节点数))
打印('Nodes generated:{:d}'。格式(num_generated))
################################################################
###Astar实现的框架代码。在这里填写。
################################################################
阿斯塔级:
"""
搜索。
-“问题”是一个谜题实例。
"""
定义初始化(自我,问题):
自我问题
self.init_state=problem.init_state
self.num_=0
self.num_generated=1
def selectState(自我、状态列表):
'''
根据f(n)=g(n)+h(n)选择要扩展的最低成本节点
'''
lowestCostPath=listOfStates[0]。路径成本
索引=int(1)
lowestNodeIndex=int(0)
而索引!=len(状态列表):
scannedPathCost=listOfStates[index]。路径成本
如果索引<扫描路径成本:
最低成本路径=扫描路径成本
最低节点索引=索引
指数+=1
返回状态列表[最低节点索引]
def f(自身、节点、方法):
'''
返回从根节点到节点的成本的下限估计值
向目标前进。
'''
返回node.path\u成本+self.h(节点,方法)
def GetManhattainstance(自身,节点):
'''
计算给定状态的曼哈顿距离
'''
迭代器=int(0)
misplacedCount=int(0)
总距离=整数(0)
而迭代器!=len(节点状态):
如果迭代器!=node.state[iterator]和node.state[iterator]!=0:
MISPLOCEDCOUNT=MISPLOCEDCOUNT+1
xCurrent=int(节点状态[迭代器]/3)
yCurrent=int(节点状态[迭代器]%3)
xDesired=int(迭代器/3)
yDesired=int(迭代器%3)
总距离=总距离+int(abs(xCurrent-xDesired))+int(abs(yCurrent-yDesired))
迭代器=迭代器+1
返回总距离+错位计数
def h(self,node,method='man'):
'''
返回从节点到目标的成本的下限估计值
使用不同的启发式。
'''
################################################################
###你的代码在这里。
################################################################
如果方法=='man':
self.getManhattandInstance(节点)
返回-1
elif方法=='rowcol':
返回-1#计算rowcol启发式
elif方法==‘错位’:
return-1#计算错位的瓷砖数量
elif方法=='null':
返回-1#计算空启发式
其他:
返回0
def方法_统计数据(自
Traceback (most recent call last): File "/Users/-/Downloads/HW1 2/code/my_hw1.py", line 214, in <module>
solution = solver.solve() File "/Users/-/Downloads/HW1 2/code/my_hw1.py", line 200, in solve
anotherFunction(self, node, method) NameError: name 'anotherFunction' is not defined [Finished in 0.1s with exit code 1]