0

Hi guys I am Start Learning Python. The way my Breath First Search using Dictionary Graph is wrong. I got an error and my code is

graphs = {
    'a': {'b': 3, 'c': 4, 'd': 7},
    'b': {'c': 1, 'f': 5},
    'c': {'f': 6, 'd': 2},
    'd': {'e': 3, 'g': 6},
    'e': {'g': 3, 'h': 4},
    'f': {'e': 1, 'h': 8},
    'g': {'h': 2},
    'h': {'g': 2}
}

here I what I tried.

def bfs_paths(graphs, start, goal):
    queue = [(start, [start])]
    while queue:
        (vertex, path) = queue.pop(0)
        for next in graphs[vertex] - set(path):
            if next == goal:
                yield path + [next]
            else:
                queue.append((next, path + [next]))
    return queue

def shortest_path(graph, start, goal):
    try:
        return next(bfs_paths(graph, start, goal))
    except StopIteration:
        return None

print(shortest_path(graphs, 'a', 'c'))

1 Answers1

0

You are indeed correct in assuming that the operation

graphs[vertex] - set(path)

between a dictionary and a set is not valid. Python would need some default (and likely non-intuitive) behavior about using either the dictionary key or value for such a set difference. Instead try changing your for loop to this:

for next in graphs[vertex]:
        if next in set(path):
            continue

This will achieve the result you are looking for.

somil
  • 360
  • 6
  • 20