Jump to content

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

Featured Replies

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

 

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

Please sign in to comment

You will be able to leave a comment after signing in

Sign In Now

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.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.