def buildGraphFromAdjacencyList(graph): g = Graph() for vertex, neighbors in graph.items(): for neighbor in neighbors: g.addEdge(vertex, neighbor) return g
def buildGraph(wordFile): dic = {} g = Graph() def read_file_line(wordFile): with open(wordFile, 'r') as wfile: while True: blockline = wfile.readline() # 调用readlines()一次读取所有内容并按行返回list if blockline: yield blockline.strip() else: return # create buckets of words that differ by one letter for line in read_file_line(wordFile): word = line[:-1] for i in range(len(word)): bucket = word[:i] + '_' + word[i + 1:] if bucket in dic: dic[bucket].append(word) else: dic[bucket] = [word] # add vertices and edges for words in the same bucket for bucket in dic.keys(): for word1 in dic[bucket]: for word2 in dic[bucket]: if word1 != word2: g.addEdge(word1, word2) return g
def knightGraph(bdSize): ktGraph = Graph() for row in range(bdSize): for col in range(bdSize): nodeId = posToNodeId(row, col, bdSize) newPositions = genLegalMoves(row, col, bdSize) for e in newPositions: nid = posToNodeId(e[0], e[1], bdSize) ktGraph.addEdge(nodeId, nid) return ktGraph
def main(): ''' num_vertices = 5 e0 = (2,3) e1 = (3,1) e2 = (1,0) e3 = (0,2) e4 = (0,4) e5 = (3,4) edges = [e0, e1, e2, e3, e4, e5] ''' num_vertices = 5 e0 = (0,1) e1 = (0,3) e2 = (0,4) e3 = (1,2) e4 = (1,3) e5 = (3,2) e6 = (3,0) e7 = (3,4) edges = [e0, e1, e2, e3, e4, e5, e6, e7] graph = Graph(num_vertices, edges) is_visited = [False] * num_vertices # DFS print("DFS : Order in which nodes were visited") stack = Stack() stack.push(0) is_visited[0] = True while not stack.is_empty: current_vertex = stack.pop() print(current_vertex) for neighbor in graph.get_neighbors(current_vertex): if not is_visited[neighbor]: is_visited[neighbor] = True stack.push(neighbor)
def main(): ''' num_vertices = 5 e0 = (2,3) e1 = (3,1) e2 = (1,0) e3 = (0,2) e4 = (0,4) e5 = (3,4) edges = [e0, e1, e2, e3, e4, e5] ''' num_vertices = 5 e0 = (0,1) e1 = (0,3) e2 = (0,4) e3 = (1,2) e4 = (1,3) e5 = (3,2) e6 = (3,0) e7 = (3,4) edges = [e0, e1, e2, e3, e4, e5, e6, e7] graph = Graph(num_vertices, edges) is_visited = [False] * num_vertices # BFS print("BFS : Order in which nodes were visited") queue = Queue() queue.enqueue(0) is_visited[0] = True while not queue.is_empty: current_vertex = queue.dequeue() print(current_vertex) for neighbor in graph.get_neighbors(current_vertex): if not is_visited[neighbor]: queue.enqueue(neighbor) is_visited[neighbor] = True
# This is a short test file, given to you to ensure that our grading scripts can grade your file. # Please do not modify it. # You should only submit "graph_adjacency_list.py", "graph_edge_list.py", and "shortest_path.py". # This tests the simplest case: adding a single edge to the graph and then checking whether has_edge # confirms the edge's existance and that get_neighbors on the first node returns the second node. from graph_adjacency_list import Graph as AdjacencyGraph from graph_edge_list import Graph as EdgeGraph import sys try: print("Testing adjacency list graph...") adjacency_graph = AdjacencyGraph() adjacency_graph.add_edge('a', 'b', 1) if not adjacency_graph.has_edge('a', 'b'): print( "Your code ran, but did NOT give True when checking whether the graph has an edge ('a', 'b') after adding edge ('a', 'b', 1)." ) else: print( "Your code ran, and it correctly output True when checking whether the graph has an edge ('a', 'b') after adding edge ('a', 'b', 1)." ) except: print( "Your code produced this error when adding edge ('a', 'b', 1) or checking has_edge('a', 'b')." ) print(sys.exc_info()[0]) try: if adjacency_graph.get_neighbors('a') != [('b', 1)]: print(
if proposed_dist < shortest_distance[neighbor_node]: shortest_distance[neighbor_node] = proposed_dist previous_node[neighbor_node] = curr_node # work backgrounds through the previous node dict and save path curr = target while curr != source: short_path.insert(0, curr) # insert at beginning of list curr = previous_node[curr] # get previous node short_path.insert(0, curr) # insert the last, source node return (short_path, shortest_distance[target]) adjacency_graph = Graph() ## # adjacency_graph.add_edge('a', 'c', 15) # adjacency_graph.add_edge('b', 't', 1) # adjacency_graph.add_edge('d', 't', 1) # adjacency_graph.add_edge('a', 't', 21) # adjacency_graph.add_edge('b', 'u', 1) # adjacency_graph.add_edge('b', 't', 6) # adjacency_graph.add_edge('u', 't', 2) # adjacency_graph.add_edge('c', 't', 20) # print shortest_path(adjacency_graph, 'a', 't') graph1 = Graph() graph1.add_edge('t', 'a', 5)
# This is a short test file, given to you to ensure that our grading scripts can grade your file. # Please do not modify it. # You should only submit "graph_adjacency_list.py", "graph_edge_list.py", and "shortest_path.py". # This tests the simplest case: adding a single edge to the graph and checking the shortest path from one node to the other. from graph_adjacency_list import Graph as AdjacencyGraph from graph_edge_list import Graph as EdgeGraph from shortest_path import shortest_path import sys try: print("Testing with adjacency list graph...") adjacency_graph = AdjacencyGraph() adjacency_graph.add_edge('a', 'b', 1) if shortest_path(adjacency_graph, 'a', 'b') != (['a', 'b'], 1): print( "Your code ran, but did NOT output the shortest distance from 'a' to 'b' when your adjacency list graph had the edge ('a', 'b', 1) added." ) else: print( "Your code ran, and it correctly output the shortest distance from 'a' to 'b' when your adjacency list graph had the edge ('a', 'b', 1) added." ) except: print( "Your code produced this error when adding edge ('a', 'b', 1) to the adjacency list graph or getting the shortest path from 'a' to 'b'." ) print(sys.exc_info()[0]) try: print("Testing with edge list graph...")
# This is a short test file, given to you to ensure that our grading scripts can grade your file. # Please do not modify it. # You should only submit "graph_adjacency_list.py", "graph_edge_list.py", and "shortest_path.py". # This tests the simplest case: adding a single edge to the graph and checking the shortest path from one node to the other. from graph_adjacency_list import Graph as AdjacencyGraph from graph_edge_list import Graph as EdgeGraph from shortest_path import shortest_path import sys try: print("Testing with adjacency list graph...") adjacency_graph = AdjacencyGraph() adjacency_graph.add_edge('a', 'b', 1) if shortest_path(adjacency_graph, 'a', 'b') != (['a', 'b'], 1): print "Your code ran, but did NOT output the shortest distance from 'a' to 'b' when your adjacency list graph had the edge ('a', 'b', 1) added." else: print "Your code ran, and it correctly output the shortest distance from 'a' to 'b' when your adjacency list graph had the edge ('a', 'b', 1) added." except: print "Your code produced this error when adding edge ('a', 'b', 1) to the adjacency list graph or getting the shortest path from 'a' to 'b'." print sys.exc_info()[0] try: print("Testing with edge list graph...") edge_graph = EdgeGraph() edge_graph.add_edge('a', 'b', 1) edge_graph.add_edge('b', 'c', 2) edge_graph.add_edge('c', 'd', 3) edge_graph.add_edge('a', 'f', 1)
# This is a short test file, given to you to ensure that our grading scripts can grade your file. # Please do not modify it. # You should only submit "graph_adjacency_list.py", "graph_edge_list.py", and "shortest_path.py". # This tests the simplest case: adding a single edge to the graph and checking the shortest path from one node to the other. from graph_adjacency_list import Graph as AdjacencyGraph from graph_edge_list import Graph as EdgeGraph from shortest_path import shortest_path import sys try: print("Testing with adjacency list graph...") adjacency_graph = AdjacencyGraph() adjacency_graph.add_edge('a', 'b', 1) adjacency_graph.add_edge('a', 'c', 2) adjacency_graph.add_edge('b', 'd', 3) adjacency_graph.add_edge('c', 'e', 5) adjacency_graph.add_edge('d', 'e', 2) adjacency_graph.add_edge('d', 'f', 4) adjacency_graph.add_edge('e', 'f', 1) if shortest_path(adjacency_graph, 'a', 'f') != (['a', 'b', 'd', 'e', 'f' ], 7): print( "Your code ran, but did NOT output the shortest distance from 'a' to 'f' when your adjacency list graph had the edge ('e', 'f', 1) added." ) else: print( "Your code ran, and it correctly output the shortest distance from 'a' to 'f' when your adjacency list graph had the edge ('e', 'f', 1) added." ) except:
print('min_value is now:',min_value) print('min_key is now: ',min_key) #select key from Q and not S with shortest distance from s --> maintains invariant u = min_key if u == target: return d[u] S.add(u) return ([],float("inf")) # YOUR CODE HERE if __name__ == "__main__": # adjacency_graph is type dict _graph = AdjacencyGraph() print('AdjacencyGraph:') #edge_graph is type list # _graph = EdgeGraph() # print('EdgeGraph:') _graph.add_edge('s','2',9) _graph.add_edge('s','6',14) _graph.add_edge('s','7',15) _graph.add_edge('2','3',24) _graph.add_edge('6','3',18) _graph.add_edge('6','5',30) _graph.add_edge('6','7',5) _graph.add_edge('3','5',2) _graph.add_edge('3','t',19) _graph.add_edge('4','t',6)
def test_dijkstra(self): # Example from https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm g = Graph() g.addEdge(1, 2, 7) g.addEdge(1, 3, 9) g.addEdge(2, 3, 10) g.addEdge(1, 6, 14) g.addEdge(2, 4, 15) g.addEdge(3, 6, 2) g.addEdge(3, 4, 11) g.addEdge(4, 5, 6) g.addEdge(5, 6, 9) dist = g.bestPath_Dijkstra(1, 5) self.assertEqual(20, dist)
from graph_adjacency_list import Graph if __name__ == '__main__': graph = Graph(5) graph.add_edge(0, 1) graph.add_edge(0, 4) graph.add_edge(1, 2) graph.add_edge(1, 3) graph.add_edge(1, 4) graph.add_edge(2, 3) graph.add_edge(3, 4) graph.print_graph()
# cost_func = lambda u, v, e, prev_e: e['cost'] # test_function = find_path(graph, 'a', 'c', cost_func=cost_func) # if shortest_path(edge_graph, 's', 't') != (test_function[0], test_function[3]): # print("pass edge_graph") # else: # break # if shortest_path(adjacency_graph, 's', 't') != (test_function[0], test_function[3]): # print("pass adjacency_graph") # else: # break ####################### TEST 0 try: adjacency_graph = AdjacencyGraph() adjacency_graph.add_edge('s', 'a', 4) adjacency_graph.add_edge('a', 't', 3) adjacency_graph.add_edge('s', 'b', 5) adjacency_graph.add_edge('b', 't', 5) if shortest_path(adjacency_graph, 's', 't') != (['s', 'a', 't'], 7): print("ERROR: TEST 0A, WRONG DISTANCE") else: print("pass test 0A") except: print("ERROR: TEST 0A, ADDING EDGE") print(sys.exc_info()[0]) try: edge_graph = EdgeGraph() edge_graph.add_edge('s', 'a', 4)