开发者

function in python

In a function, I need to perform some logic that requires me to call a function inside a function. What I did with this, like:

def dfs(problem):
   stack.push(bache)
   search(root)              
   while stack.isEmpty() != 0:


  def search(ve开发者_StackOverflow中文版rtex):
     closed.add(vertex)
     for index in sars:
        stack.push(index)
        return stack

In the function, dfs, I am using search(root), is this is the correct way to do it?

I am getting an error: local variable 'search' referenced before assignment


There are many mysterious bug-looking aspects in your code. The wrong order of definition (assuming you do need the search function to be a nested one) and the syntax error from the empty while loop have already been observed, but there are more...:

def dfs(problem):
   stack.push(bache)
   search(root)              

what's bache, what's stack, what's root? If they're all global variables, then you're overusing globals -- and apparently nowhere ever using the argument problem (?!).

   while stack.isEmpty() != 0:

what's this weird-looking method isEmpty? IOW, what type is stack (clearly not a Python list, and that's weird enough, since they do make excellent LIFO stacks;-)...? And what's ever going to make it empty...?

  def search(vertex):
     closed.add(vertex)

...don't tell me: closed is yet another global? Presumably a set? (I remember from a few of your Qs back that you absolutely wanted to have a closed dict, not set, even though I suggested that as a possibility...

     for index in sars:

...and what's sars?!

        stack.push(index)
        return stack

what a weird "loop" -- one that executes exactly once, altering a global variable, and then immediately returns that global variable (?) without doing any of the other steps through the loop. Even if this is exactly what you mean (push the first item of sars, period) I don't recommend hiding it in a pseudo-loop -- it seriously looks like a mystery bug just waiting to happen;-).


You need to de-indent your search function. The way you have it set up right now you are defining your search function as a part of the completion of your dfs call. Also, encapsulation in a class would help.


Thats the wrong order. Try this:

def dfs(problem):
    def search(vertex):
        closed.add(vertex)
        for index in sars:
            stack.push(index)
            return stack

    stack.push(bache)
    search(root)              
    while stack.isEmpty() != 0:


Either define search before you call it, or define it outside of dfs.


  1. you have to define the function before using it
  2. root doesn't seem to be available in your scope - make sure it's reachable


You don't have body to your for your while loop. That is probably causing problems parsing the code. I would also suggest putting the local function definition before it is used, so it is easier to follow.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜