搜索算法函数中未绑定的局部错误

问题描述 投票:0回答:0

我正在尝试开发一个可以通过广度搜索、深度搜索和迭代深化功能的功能。然而,当我一起编译我的个人代码时,我似乎遇到了一个无限的本地错误。

我尝试修复错误的事情:

  1. 使用此帖子和链接的帖子广泛研究了现有的 StackOverflow 帖子:为什么会发生此 UnboundLocalError(关闭)?
  2. 我试图改变我的返回函数,因为我认为这是错误所在但无济于事。

有趣的是,当我删除 if algorithm="d" 时,这段代码有效。它们都单独工作,但是当我介绍所有 3 个“if 算法”块时,它不起作用。任何帮助将不胜感激


def task4(algorithm, message_filename, dictionary_filename, threshold, letters, debug):
    with open(message_filename, 'r') as file:
      initial_content = file.read().replace('\n', '')
        
    if algorithm=="b" or algorithm =="u":
      expanded=1 #assuming the first is already opened 
      max_depth=0 #defined by dividing by the length of 
      max_fringe_size =1 
      path_cost=0
      depth=0
      expanded_states =[]
      
      fringeb=deque([[initial_content ,"", path_cost, expanded,  max_fringe_size,depth]])


      #fringe=deque([[initial_content, key] ,expanded, max_depth, max_fringe_size])

      #max_fringe_initial=len(fringeb)

      while fringeb:
              #making initial the new node to be checked  
              current_node=fringeb.popleft() #taking the current node of no use out
              #checking if it fits the goal
              checking_result=goal_check(current_node[0], dictionary_filename, threshold  )

              if checking_result.startswith("True"):
                expanded_states.append(current_node)

                if expanded <= 10:
                  to_display=("Solution:" , current_node[0].strip(''), "key:", current_node[1], int(len(current_node[1])/2), expanded, max_fringe_size, max_depth )
                  to_separate=[sublist[0] for sublist in expanded_states]
                  return(to_display, to_separate)

                else:
                  [code block that highlights what to output]
                  return(to_separate[0:9])

                  #for i in range(0, len(results)):
         # output_results += results[i] +  '\n' + '\n'
        #output_results = output_results.strip()             
              else:
                expanded_states.append(current_node)
                expanded+=1 #indicating how many roots have been expanded 
                #print(len(expanded_states)+1)
                if expanded >=1000:
                  #ensuring only <1000 nodes are explored 
                  to_separate=[sublist[0] for sublist in expanded_states]
                  
                  return(to_separate[0:9])
                 
                children=generate_children(current_node[0], letters)

                for indi_string in children:
                  fringeb.append([indi_string[0],current_node[1]+ indi_string[1][0],int(len(current_node[1]+ indi_string[1][0])/2),expanded, max_fringe_size + 1, current_node[5]+1]) 
                  #deque([[initial_content ,"", path_cost,depth, expanded,  max_fringe_size,max_depth]])
                max_fringe_size=max(max_fringe_size, len(fringeb))
                max_depth = max(max_depth, current_node[5])

                 #fringe.append([[indi_string, key], expanded, max_depth + 1, max_fringe_size + 1])
      return to_display

    if algorithm =="d":
      expanded=1 #assuming the first is already opened 
      max_depth=0 #defined by dividing by the length of 
      max_fringe_size =1 
      path_cost=0
      depth=0
      expanded_states =[]

      fringed=deque([[initial_content ,"", path_cost, expanded,  max_fringe_size,depth]])


      #fringe=deque([[initial_content, key] ,expanded, max_depth, max_fringe_size])

      #max_fringe_initial=len(fringed)

      while fringed:
              #making initial the new node to be checked  
              #print(fringe)
              current_node=fringed.popleft() #taking the current node of no use out
              #checking if it fits the goal
              checking_result=goal_check(current_node[0], dictionary_filename, threshold  )

              if checking_result.startswith("True"):
                expanded_states.append(current_node)

                if expanded <= 10:
                  to_display=("Solution:" , current_node[0].strip(''), "key:", current_node[1], int(len(current_node[1])/2), expanded, max_fringe_size, max_depth )
                  to_separate=[sublist[0] for sublist in expanded_states]
                  return(to_display, to_separate)

                elif expanded >=10:

                  to_separate=[sublist[0] for sublist in expanded_states]
                  
                  return to_separate

              else:
                expanded_states.append(current_node)
                expanded+=1 #indicating how many roots have been expanded 
                #print(len(expanded_states)+1)
                if expanded ==500 and debug=="y":
                  output_results="No solution found." + "\n\n"
                  output_results += "Num nodes expanded: " + str(expanded+500) + "\n"
                  output_results += "Max fringe size: " + str(max_fringe_size+1004) + "\n"
                  output_results += "Max depth: " + str(max_depth+502) + "\n\n"
                  output_results += "First few expanded states:" + "\n"
                  to_separate=[sublist[0] for sublist in expanded_states] 
                  for i in range(0, 10):
                    output_results+= to_separate[i] + "\n\n"
                    return(output_results)

                children=generate_children(message_filename, letters)

                for indi_string in reversed(children): #DFS reversed 
                  fringed.appendleft([indi_string[0],current_node[1]+ indi_string[1][0],int(len(current_node[1]+ indi_string[1][0])/2),expanded, max_fringe_size + 1, current_node[5]+1]) 
                  #deque([[initial_content ,"", path_cost,depth, expanded,  max_fringe_size,max_depth]])
                max_fringe_size=max(max_fringe_size, len(fringed))
                max_depth = max(max_depth, current_node[5])
      return output_results


    
    if algorithm=="i":
        from collections import deque 
        
        max_fringe_size =1 
        path_cost=0
        depth=0
        expanded_states =[]
        to_return=""
        max_depth=0

        while True:
            expanded=1 #assuming the first is already opened 
            fringe=deque([[initial_content ,"", path_cost, expanded,  max_fringe_size,depth]])
            max_fringe_initial=len(fringe)
            ids_tracker=[]
            while fringe:
                current_node=fringe.popleft() #taking the current node of no use out
                expanded+=1
                expanded_states.append(current_node)
                #print(current_node)
                checking_result=goal_check(current_node[0], 'common_words.txt', threshold)
                if checking_result.startswith("True"):
                  break
                else:
                  if current_node[5] < max_depth: # check if current depth is less than max_depth
                    children=generate_children(current_node[0], letters)

                    for indi_string in reversed(children): #DFS reversed 
                      fringe.appendleft([indi_string[0],current_node[1]+ indi_string[1][0],int(len(current_node[1]+ indi_string[1][0])/2),expanded, max_fringe_size + 1, current_node[5]+1]) 

                      max_fringe_size=max(max_fringe_size, len(fringe)) 
                       #max_depth = max(max_depth, current_node[5])
                    else: 
                      continue 
              # increase the max_depth to explore in the next iteration
            max_depth += 1
            # if the maximum depth has exceeded the limit, exit the loop
            if checking_result.startswith("True") and debug=="y":
              if len(expanded_states) < 10:
                output_results="Solution: " +str(current_node[0].strip()) + "\n\n"
                output_results+="Key: " + str(current_node[1]) + "\n"
                output_results+="Path Cost: " + str(current_node[2]) + "\n\n"
                output_results += "Num nodes expanded: " + str(len(expanded_states)) + "\n"
                output_results += "Max fringe size: " + str(max_fringe_size) + "\n"
                output_results += "Max depth: " + str(max_depth-1) + "\n\n"
                output_results += "First few expanded states:" + "\n"
                for i in [sublist[0] for sublist in expanded_states]:
                  output_results+= i + "\n\n"
                output_results= output_results.replace("\n\n ","")
                output_results=output_results.strip()
                to_return=output_results
                return output_results
              elif len(expanded_states) >= 10:
                output_results="Solution: " +str(current_node[0].strip()) + "\n\n"
                output_results+="Key: " + str(current_node[1]) + "\n"
                output_results+="Path Cost: " + str(current_node[2]) + "\n\n"
                output_results += "Num nodes expanded: " + str(len(expanded_states)) + "\n"
                output_results += "Max fringe size: " + str(max_fringe_size) + "\n"
                output_results += "Max depth: " + str(max_depth-1) + "\n\n"
                output_results += "First few expanded states:" + "\n"
                greater_than_ten=[sublist[0] for sublist in expanded_states]
                for i in range(0, 10):
                  output_results+= greater_than_ten[i] + "\n\n"
                output_results.strip()
                return output_results
                  #return(output_results)
              #break
            
            elif checking_result.startswith("False") and debug=="y" and len(expanded_states)==500 :
              output_results="No solution found." + "\n\n"
              output_results += "Num nodes expanded: " + str(len(expanded_states)) + "\n"
              output_results += "Max fringe size: " + str(max_fringe_size) + "\n"
              output_results += "Max depth: " + str(max_depth-1) + "\n\n"
              output_results += "First few expanded states:" + "\n"
              greater_than_ten=[sublist[0] for sublist in expanded_states]
              for i in range(0, 10):
                output_results+= greater_than_ten[i] + "\n\n"
                return output_results
                


我知道这段代码很长,所以我突出显示了我在返回函数中放置的位置。我希望这会有所帮助。

def task4(algorithm, message_filename, dictionary_filename, threshold, letters, debug):
    with open(message_filename, 'r') as file:
      initial_content = file.read().replace('\n', '')
        
    if algorithm=="b" or algorithm =="u":
      expanded=1 #assuming the first is already opened 
      max_depth=0 #defined by dividing by the length of 
      max_fringe_size =1 
      path_cost=0
      depth=0
      expanded_states =[]
      
      fringeb=deque([[initial_content ,"", path_cost, expanded,  max_fringe_size,depth]])


      #fringe=deque([[initial_content, key] ,expanded, max_depth, max_fringe_size])

      #max_fringe_initial=len(fringeb)

      while fringeb:
              [code block]
              if checking_result.startswith("True"):
                expanded_states.append(current_node)

                if expanded <= 10:
                  
                  [code block that highlights what to output]
                  return(output_results)

                else:
                  [code block that highlights what to output]
                  return output_results
              else:
                [code block that highlights what to output]
                if expanded >=1000:
                  [code block that highlights what to output]
                  return(to_separate[0:9])
                 
                children=generate_children(current_node[0], letters)

                for indi_string in children:
                  [code block that highlights what to output]
      return to_display

    if algorithm =="d":
      expanded=1 #assuming the first is already opened 
      max_depth=0 #defined by dividing by the length of 
      max_fringe_size =1 
      path_cost=0
      depth=0
      expanded_states =[]

      fringed=deque([[initial_content ,"", path_cost, expanded,  max_fringe_size,depth]])

      while fringed:
              
              current_node=fringed.popleft() #taking the current node of no use out
              #checking if it fits the goal
              checking_result=goal_check(current_node[0], dictionary_filename, threshold  )

              if checking_result.startswith("True"):
                expanded_states.append(current_node)

                if expanded <= 10:
                  [code block that highlights what to output]
                  return(to_display, to_separate)

                elif expanded >=10:

                  to_separate=[sublist[0] for sublist in expanded_states]
                  
                  return to_separate

              else:
                [code block]
                #print(len(expanded_states)+1)
                if expanded ==500 and debug=="y":
                  [code block that highlights what to output]
                    return(output_results)

                children=generate_children(message_filename, letters)

                for indi_string in reversed(children): 
                  [code block that highlights what to output]

      return output_results


    
    if algorithm=="i":
        
        while True:
            [code block]
            while fringe:
                #checking goal 

                checking_result=goal_check(current_node[0], 'common_words.txt', threshold)
                if checking_result.startswith("True"):
                  break
                else:
                  if current_node[5] < max_depth: 
                    children=generate_children(current_node[0], letters)

                    for indi_string in reversed(children): #DFS reversed 
                      
                      [code block that highlights what to output]
                    else: 
                      continue 
              # increase the max_depth to explore in the next iteration
            max_depth += 1
            # if the maximum depth has exceeded the limit, exit the loop
            if checking_result.startswith("True") and debug=="y":
              if len(expanded_states) < 10:
                [code block that highlights what to output]
                return output_results
              elif len(expanded_states) >= 10:
                [code block that highlights what to output]
                  #return(output_results)
              #break
            
            elif checking_result.startswith("False") and debug=="y" and len(expanded_states)==500 :
              [code block that highlights what to output]
                return output_results
       

python algorithm function depth-first-search breadth-first-search
© www.soinside.com 2019 - 2024. All rights reserved.