I apologize in advance if I’m asking a somewhat obvious question, but I’m somewhat new to Python and am still figuring out the kinks of it.
I’m working on a script to search through a tree, starting at node A and (hopefully) terminating at goal node M. My work is based off of the example code provided in Artificial Intelligence: A Modern Approach, specifically this Python search script.
I run into difficulties when attempting to execute a breadth_first_search, where I get the following error:
...
update(self, state=state, parent=parent, action=action,
path_cost=path_cost, depth=0)
NameError: global name 'update' is not defined
I am attempting to use the update() function to update the state, parent, children, etc. of a node, where the code is as follows:
class Node:
def __init__(self, state, parent=None, action=None, path_cost=0):
"Create a search tree Node, derived from a parent by an action."
update(self, state=state, parent=parent, action=action,
path_cost=path_cost, depth=0)
if parent:
self.depth = parent.depth + 1
I’ve been stuck on this for a while now and am unsure how to proceed. I would greatly appreciate any suggestions to help fix this problem. Thank you!
4
Answers
The link you have given for
update
is not a global function, but a member of dictionary, so must be called on a dictionary. If your class had one, called e.g. dataEdit
Furthermore, not the code you link to also has a utils.py here
This defines a global update function that will do what
Node
is trying to do:You probably need to get the whole svn repo, with their directory structure in order to get this working.
update()
is a method of the builtindict
type. Note the section under which that method’s documentation resides. If you were using a dictionary, let’s call itmy_dict
, you’d do something like this:But I’m not sure you are using a dictionary for your code. The link you posted does not define the
update()
function. It must be imported with the line at the top of the example code:This assumes that in
utils.py
there is a function namedupdate
. If that’s the case, you need to include thatimport
statement in your file.update()
is an instance method for dictionary objects. Unless you define the same method for yourNode
:have a dictionary within the class that can be
update
d:or create or
import
a function that takes aNode
object:it will not be available.
The update() function you linked is a method of the dict type. If your object is a subclass of dict ( or a subclass of a subclass ), you should be able to call