def test(): # Create an example graph vertices = {'A', 'B', 'C', 'D', 'E'} edges = {('A', 'B', 4), ('A', 'C', 2), ('B', 'C', 1), ('B', 'D', 3), ('C', 'E', 6), ('D', 'E', 1)} graph = WeightedGraph(vertices, edges) # What's the cheapest path from A to everywhere? parents = graph.dijkstra('A') for v in graph.vertices: path = Graph.path(v, parents) print(v, path, graph.path_weight(path))
def passThrough(verticies, edges, startVertex, endVertex, passByPoint): graph = WeightedGraph(verticies, edges) result = list() parents1 = graph.dijkstra(startVertex) path1 = Graph.path(passByPoint, parents1) parents2 = graph.dijkstra(passByPoint) path2 = Graph.path(endVertex, parents2) if path1 is None or path2 is None: return "The 3 verticies are not in the same compound, so it is not possible." for anItem in path1: result.append(anItem) for i in range(1, len(path2)): result.append(path2[i]) return " -> ".join(result)
def notPassThrough(verticies, edges, startVertex, endVertex, notPassByPoint): edgesCopy = set() result = list() for aTuple in edges: if notPassByPoint not in aTuple: edgesCopy.add(aTuple) graph = WeightedGraph(verticies, edgesCopy) parents = graph.dijkstra(endVertex) path = Graph.path(startVertex, parents) for anItem in reversed(path): result.append(anItem) return " -> ".join(result)
for aWord in words: vertices.add(aWord) for i in range(len(aWord)): newWord = aWord[0:i] + "*" + aWord[i + 1:] if newWord not in specialDict: specialDict[newWord] = [aWord] else: for aConnection in specialDict[newWord]: edges.add((aWord, aConnection)) specialDict[newWord].append(aWord) # Construct the graph graph = Graph(vertices, edges) # Find word ladders while True: source = input("Source word: ") if source not in vertices: print("Unknown word:", source, "\n") continue target = input("Target word: ") if target not in vertices: print("Unknown word:", target, "\n") continue parents = graph.bfs(source) ladder = Graph.path(target, parents) print("Shortest ladder:", ladder, "\n")