Jump to content

Exception has occurred: UnboundLocalError local variable 'depth' referenced before assignment


shivajikobardan

Recommended Posts

This code is for iterative deepening depth first search in python.

 

# Python dictionary to act as an adjacency list


graph = {

  '7' : ['19','21', '14'],

  '19': ['1', '12', '31'],

  '21': [],

  '14': ['23', '6'],

  '1' : [],

  '12': [],

  '31': [],

  '23': [],

  '6' : []

}

visited=[]

goal='31'

depth=0

 

depth_limit=2

def dls(visited, graph, node,depth_limit):

    if(node==goal):

            print("goal found")

            return True

 

    

    if(depth>=0):

        #to print path

        if node not in visited:

            visited.append(node)

        

        

 

        for neighbor in graph[node]:

            dls(visited, graph, neighbor,depth_limit-1)

        

 

    return False

 

 

def iddfs(visited,graph,node):

    while True:

        solution=dls(visited,graph,node,depth_limit)

        if(solution==goal):

            print("Success goal find at depth=",depth)

            print("Path=",visited)     

        depth=depth+1

 

        

 

print("Following is the Depth-First Search")

iddfs(visited, graph, '7')[/CODE]

 

There are various pseudocodes available for this problem. They are as follows-:

I did my best to understand and implement the code but I seem to have failed. And it is getting really confusing. Can you help me?

 

 

https://www.swisstransfer.com/d/96a28f8d-968c-4dae-8762-f0f0afed6dbf

Link to comment
Share on other sites

 

45 minutes ago, shivajikobardan said:

Can you help me?

There are helpful comments and a solution applicable to this in your other thread, some feedback would be appreciated why that did or did not work: 

 

 

45 minutes ago, shivajikobardan said:

https://www.sw...

Sorry, not going to visit that link. 

 

 

Edited by Ghideon
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.