简体   繁体   中英

python - using dictionary to define a graph and find paths

I have defined a graph as the following:

adj_matrix = {'1': set('2'),
              '2': set('3'),
              '3': set(['4', '5']),
              '4': set(''),
              '5': set('6'),
              '6': set('7'),
              '7': set('8'),
              '8': set(['9', '14']),
              '9': set(['10', '11']),
              '10': set(''),
              '11': set(['12', '13']),
              '12': set(''),
              '13': set(''),
              '14': set('15'),
              '15': set('16'),
              '16': set('17'),
              '17': set(['18', '19']),
              '18': set(''),
              '19': set('')}

And I am using the following to find the path between different nodes:

def find_path(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return path
        if start not in graph:
            return None
        for node in graph[start]:
            if node not in path:
                newpath = find_path(graph, node, end, path)
                if newpath: return newpath
        return None

The issue is the function only works for nodes 1 to 14 . Like when I call p = find_path(adj_matrix, '3', '14') it works like a charm and gives me ['3', '5', '6', '7', '8', '14'] as the answer, but when I try p = find_path(adj_matrix, '3', '15') for instance, it returns None . Any ideas what is going on and how I could fix this?

for the erroneous case, when you reach '14' , available routes are shown as '1' and '5' , not as '15' . You should set a list for each set , so that you can iterate over actual values.

adj_matrix = {'1': set(['2']),
              '2': set(['3']),
              '3': set(['4', '5']),
              '4': set(''),
              '5': set(['6']),
              '6': set(['7']),
              '7': set(['8']),
              '8': set(['9', '14']),
              '9': set(['10', '11']),
              '10': set(''),
              '11': set(['12', '13']),
              '12': set(''),
              '13': set(''),
              '14': set(['15']),
              '15': set(['16']),
              '16': set(['17']),
              '17': set(['18', '19']),
              '18': set(''),
              '19': set('')}

using the adj_matrix above, it gives correct result.

here is your function with my debuggers. You can see how code flows from the terminal:

def find_path(graph, start, end, path=[]):
        path = path + [start]
        print("st:%s, end:%s, path:%s" % (start,end,path))
        if start == end:
            return path
        if start not in graph:
            return None
        print("available routes: %s" % graph[start])
        for node in graph[start]:
            if node not in path:
                print("next node: %s" % node)
                newpath = find_path(graph, node, end, path)
                if newpath: return newpath
        return None

Using your erroneous adj_matrix, it gives console output like this: (Watch closely when it comes to '14' )

C:\Users\rapac\Desktop\stackoverflow>python adjgraph.py
st:3, end:15, path:['3']
available routes: {'5', '4'}
next node: 5
st:5, end:15, path:['3', '5']
available routes: {'6'}
next node: 6
st:6, end:15, path:['3', '5', '6']
available routes: {'7'}
next node: 7
st:7, end:15, path:['3', '5', '6', '7']
available routes: {'8'}
next node: 8
st:8, end:15, path:['3', '5', '6', '7', '8']
available routes: {'9', '14'}
next node: 9
st:9, end:15, path:['3', '5', '6', '7', '8', '9']
available routes: {'11', '10'}
next node: 11
st:11, end:15, path:['3', '5', '6', '7', '8', '9', '11']
available routes: {'13', '12'}
next node: 13
st:13, end:15, path:['3', '5', '6', '7', '8', '9', '11', '13']
available routes: set()
next node: 12
st:12, end:15, path:['3', '5', '6', '7', '8', '9', '11', '12']
available routes: set()
next node: 10
st:10, end:15, path:['3', '5', '6', '7', '8', '9', '10']
available routes: set()
next node: 14
st:14, end:15, path:['3', '5', '6', '7', '8', '14']
available routes: {'5', '1'} <--- Here it is! We expect '15' here.
next node: 1
st:1, end:15, path:['3', '5', '6', '7', '8', '14', '1']
available routes: {'2'}
next node: 2
st:2, end:15, path:['3', '5', '6', '7', '8', '14', '1', '2']
available routes: {'3'}
next node: 4
st:4, end:15, path:['3', '4']
available routes: set()
None

Finally, here is the output when you use correct version of adj_matrix :

C:\Users\rapac\Desktop\stackoverflow>python adjgraph.py
st:3, end:15, path:['3']
available routes: {'4', '5'}
next node: 4
st:4, end:15, path:['3', '4']
available routes: set()
next node: 5
st:5, end:15, path:['3', '5']
available routes: {'6'}
next node: 6
st:6, end:15, path:['3', '5', '6']
available routes: {'7'}
next node: 7
st:7, end:15, path:['3', '5', '6', '7']
available routes: {'8'}
next node: 8
st:8, end:15, path:['3', '5', '6', '7', '8']
available routes: {'9', '14'}
next node: 9
st:9, end:15, path:['3', '5', '6', '7', '8', '9']
available routes: {'11', '10'}
next node: 11
st:11, end:15, path:['3', '5', '6', '7', '8', '9', '11']
available routes: {'12', '13'}
next node: 12
st:12, end:15, path:['3', '5', '6', '7', '8', '9', '11', '12']
available routes: set()
next node: 13
st:13, end:15, path:['3', '5', '6', '7', '8', '9', '11', '13']
available routes: set()
next node: 10
st:10, end:15, path:['3', '5', '6', '7', '8', '9', '10']
available routes: set()
next node: 14
st:14, end:15, path:['3', '5', '6', '7', '8', '14']
available routes: {'15'} <-- Now we're good.
next node: 15
st:15, end:15, path:['3', '5', '6', '7', '8', '14', '15']
['3', '5', '6', '7', '8', '14', '15']

Now the code behaves as you would expect. Hope it helps.

If you change your input to be

adj_matrix = {'1': set('2'),
          '2': set('3'),
          '3': set(['4', '5']),
          '4': set(''),
          '5': set('6'),
          '6': set('7'),
          '7': set('8'),
          '8': set(['9', '14']),
          '9': set(['10', '11']),
          '10': set(''),
          '11': set(['12', '13']),
          '12': set(''),
          '13': set(''),
          '14': set(['15']),
          '15': set(['16']),
          '16': set(['17']),
          '17': set(['18', '19']),
          '18': set(''),
          '19': set('')}

(I just added placed the '15', '16' and '17' in a list.) Then it works. Your issue has to do with the fact that the two digit numbers when they are alone in the set are interpreted as a string in the line for node in graph[start]: and then you loop over ['1', '5']

Also note that alternatively you could simply use integers without the quotes around every number and that would solve this issue too I think.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM