def test_addEdge(self): # Tests error alert when adding duplicate edge g = LinkedDirectedGraph() g.addVertex("A") g.addVertex("B") g.addVertex("C") g.addEdge("A", "B", 2.5) with self.assertRaises(AttributeError): g.addEdge("A", "B", 2.5)
def test_getEdge(self): # Tests error alert when getting non-existent edge g = LinkedDirectedGraph() g.addVertex("A") g.addVertex("B") g.addVertex("C") g.addEdge("A", "B", 2.5) with self.assertRaises(AttributeError): g.getEdge("Q", "P")
def createGraph(self, rep, startLabel, endLabel): """Creates a graph from rep and startLabel. Returns a message if the graph was successfully created or an error message otherwise.""" self._graph = LinkedDirectedGraph() self._startLabel = startLabel self._endLabel = endLabel edgeList = rep.split() for edge in edgeList: if not '>' in edge: # A disconnected vertex if not self._graph.containsVertex(edge): self._graph.addVertex(edge) else: self._graph = None return "Duplicate vertex" else: # Two vertices and an edge bracketPos = edge.find('>') # this finds where the ">" is colonPos = edge.find(':') # this finds where the ":" is if bracketPos == -1 or colonPos == -1 or \ bracketPos > colonPos: self._graph = None return "Problem with > or :" fromLabel = edge[:bracketPos] toLabel = edge[bracketPos + 1:colonPos] weight = edge[colonPos + 1:] if weight.isdigit(): weight = int(weight) if not self._graph.containsVertex(fromLabel): self._graph.addVertex(fromLabel) if not self._graph.containsVertex(toLabel): self._graph.addVertex(toLabel) if self._graph.containsEdge(fromLabel, toLabel): self._graph = None return "Duplicate edge" self._graph.addEdge(fromLabel, toLabel, weight) vertex = self._graph.getVertex(startLabel) if vertex is None: self._graph = None return "Start label not in graph" else: vertex.setMark() return "Graph created successfully"
def create_graph(self, rep, start_label): """创建图""" self._graph = LinkedDirectedGraph() self._start_label = start_label edge_list = rep.split() for edge in edge_list: if not '->' in edge: # 单个顶点(edge == label) if not self._graph.contain_vertex(edge): self._graph.add_vertex(edge) else: self._graph = None return "Duplicate vertex" else: # 两个顶点和一条边 bracket_pos = edge.find("->") col_on_pos = edge.find(":") if bracket_pos == -1 or col_on_pos == -1 or \ bracket_pos > col_on_pos: self._graph = None return "Problem with -> or :" from_label = edge[:bracket_pos] to_label = edge[bracket_pos + 2:col_on_pos] weight = edge[col_on_pos + 1:] if weight.isdigit(): weight = int(weight) if not self._graph.contain_vertex(from_label): self._graph.add_vertex(from_label) if not self._graph.contain_vertex(to_label): self._graph.add_vertex(to_label) if self._graph.contain_edge(from_label, to_label): self._graph = None return "Duplicate edge" self._graph.add_edge(from_label, to_label, weight) # 起始顶点 vertex = self._graph.get_vertex(start_label) if vertex == None: self._graph = None return "Start label not in graph" else: vertex.set_mark() return "Graph created successfully"
def initialize_graph(weight_matrix: np.array, label_map: dict, directed: bool): """Create a graph out of weight matrix. :param weight_matrix: 2D matrix of weights :param label_map: how each row of the matrix relates to node label :param directed: whether the graph is directed :return: the generated graph """ if directed: graph = LinkedDirectedGraph() else: graph = LinkedGraph() vert_n = len(weight_matrix) # add all vertices for i in range(vert_n): graph.add_vertex(label_map[i]) if directed: # add necessary edges for i in range(vert_n): for ii in range(vert_n): if weight_matrix[i, ii] != inf: try: graph.add_edge(label_map[i], label_map[ii], weight_matrix[i, ii]) except AttributeError: continue else: # add necessary edges with regard to symmetrical nature of the matrix for i in range(vert_n): for ii in range(i): if weight_matrix[i, ii] != inf: try: graph.add_edge(label_map[i], label_map[ii], weight_matrix[i, ii]) except AttributeError: continue print(graph) return graph
def createGraph(self, rep, startLabel): """Creates a graph from rep and startLabel. Returns a message if the graph was successfully created or an error message otherwise.""" self._graph = LinkedDirectedGraph() self._startLabel = startLabel edgeList = rep.split() for edge in edgeList: if not '>' in edge: # A disconnected vertex if not self._graph.containsVertex(edge): self._graph.addVertex(edge) else: self._graph = None return "Duplicate vertex" else: # Two vertices and an edge bracketPos = edge.find('>') colonPos = edge.find(':') if bracketPos == -1 or colonPos == -1 or \ bracketPos > colonPos: self._graph = None return "Problem with > or :" fromLabel = edge[:bracketPos] toLabel = edge[bracketPos + 1:colonPos] weight = edge[colonPos + 1:] if weight.isdigit(): weight = int(weight) if not self._graph.containsVertex(fromLabel): self._graph.addVertex(fromLabel) if not self._graph.containsVertex(toLabel): self._graph.addVertex(toLabel) if self._graph.containsEdge(fromLabel, toLabel): self._graph = None return "Duplicate edge" self._graph.addEdge(fromLabel, toLabel, weight) vertex = self._graph.getVertex(startLabel) if vertex is None: self._graph = None return "Start label not in graph" else: vertex.setMark() return "Graph created successfully"
class GraphDemoModel(object): """The model class for the application.""" def __init__(self): self._graph = None self._startLabel = None def createGraph(self, rep, startLabel): """Creates a graph from rep and startLabel. Returns a message if the graph was successfully created or an error message otherwise.""" self._graph = LinkedDirectedGraph() self._startLabel = startLabel edgeList = rep.split() for edge in edgeList: if not '>' in edge: # A disconnected vertex if not self._graph.containsVertex(edge): self._graph.addVertex(edge) else: self._graph = None return "Duplicate vertex" else: # Two vertices and an edge bracketPos = edge.find('>') colonPos = edge.find(':') if bracketPos == -1 or colonPos == -1 or \ bracketPos > colonPos: self._graph = None return "Problem with > or :" fromLabel = edge[:bracketPos] toLabel = edge[bracketPos + 1:colonPos] weight = edge[colonPos + 1:] if weight.isdigit(): weight = int(weight) if not self._graph.containsVertex(fromLabel): self._graph.addVertex(fromLabel) if not self._graph.containsVertex(toLabel): self._graph.addVertex(toLabel) if self._graph.containsEdge(fromLabel, toLabel): self._graph = None return "Duplicate edge" self._graph.addEdge(fromLabel, toLabel, weight) vertex = self._graph.getVertex(startLabel) if vertex is None: self._graph = None return "Start label not in graph" else: vertex.setMark() return "Graph created successfully" def getGraph(self): """Returns the string rep of the graph or None if it is unavailable""" if not self._graph: return None else: return str(self._graph) def getStartLabel(self): return self._startLabel def run(self, algorithm): """Runs the given algorithm on the graph and returns its result, or None if the graph is unavailable.""" if self._graph is None: return None else: return algorithm(self._graph, self._startLabel)
""" File: testdirected.py """ from graph import LinkedDirectedGraph # Create a directed graph using an adjacency list g = LinkedDirectedGraph() # Add vertices labeled A, B, and C to the graph and print it g.addVertex("A") g.addVertex("B") g.addVertex("C") print("Expect vertices ABC and no edges: \n" + str(g)) # Insert edges with weight 2.5 and print the graph g.addEdge("A", "B", 2.5) g.addEdge("B", "C", 2.5) g.addEdge("C", "B", 2.5) print("Expect same vertices and edges AB BC CB all with weight 2.5: \n" + str(g)) # Mark all the vertices for vertex in g.vertices(): vertex.setMark() # Print the vertices adjacent to vertex B print("Expect vertices adjacent to B, namely C:") v = g.getVertex("B") for neighbor in g.neighboringVertices(v.getLabel()): print(neighbor)
File: testcourses.py Author: Leigh Stauffer Project 12 Builds a graph of the courses in the CS curriculum at W&L """ from graph import LinkedDirectedGraph from linkedstack import LinkedStack from linkedqueue import LinkedQueue from grid import Grid from arrays import Array # Create a directed graph using an adjacency list. chart = LinkedDirectedGraph() # Add vertices with course labels and print the graph. courseLyst = ["CSCI111", "CSCI210", "CSCI112", "CSCI209", "CSCI211", "CSCI312", "CSCI313", "MATH121", "MATH102", "MATH122", "MATH222"] for item in courseLyst: chart.addVertex(item) print("The chart: \n" + str(chart)) # Insert edges with weight 1 and print the graph. chart.addEdge("CSCI111", "CSCI210", 1) chart.addEdge("CSCI111", "CSCI112", 1) chart.addEdge("CSCI210", "CSCI312", 1)
""" File: shorttest.py """ from graph import LinkedDirectedGraph g = LinkedDirectedGraph() # Insert vertices g.addVertex("A") g.addVertex("B") g.addVertex("C") g.addVertex("D") g.addVertex("E") # Insert weighted edges g.addEdge("A", "B", 3) g.addEdge("A", "C", 2) g.addEdge("B", "D", 1) g.addEdge("C", "D", 1) g.addEdge("D", "E", 2) print g print "Neighboring vertices of A:" for vertex in g.neighboringVertices("A"): print vertex print "Incident edges of A:" for edge in g.incidentEdges("A"): print edge
""" File: testdirected.py Project 12.10 Tests +, ==, in, and clone operations. """ from graph import LinkedDirectedGraph # Create a directed graph using an adjacency list g = LinkedDirectedGraph("ABCD") # Insert edges with different weights and print the graph g.addEdge("A", "B", 1) g.addEdge("B", "C", 3) g.addEdge("C", "B", 2) g.addEdge("B", "D", 5) print("The graph:", g) # Test the in operator print("Expect True:", "B" in g) print("Expect False:", "E" in g) # Test the clone method g2 = g.clone() print("The clone:", g2) #Test + g3 = LinkedDirectedGraph("EFG") g3.addEdge("E", "F", 6) g3.addEdge("G", "E", 8)
File: testcourses.py Author: Leigh Stauffer Project 12 Builds a graph of the courses in the CS curriculum at W&L """ from graph import LinkedDirectedGraph from linkedstack import LinkedStack from linkedqueue import LinkedQueue from grid import Grid from arrays import Array # Create a directed graph using an adjacency list. chart = LinkedDirectedGraph() # Add vertices with course labels and print the graph. courseLyst = [ "CSCI111", "CSCI210", "CSCI112", "CSCI209", "CSCI211", "CSCI312", "CSCI313", "MATH121", "MATH102", "MATH122", "MATH222" ] for item in courseLyst: chart.addVertex(item) print("The chart: \n" + str(chart)) # Insert edges with weight 1 and print the graph. chart.addEdge("CSCI111", "CSCI210", 1) chart.addEdge("CSCI111", "CSCI112", 1) chart.addEdge("CSCI210", "CSCI312", 1)
""" File: testdirected.py Project 12.1 Tests preconditions on methods. Uncomment lines of code to test for exceptions. """ from graph import LinkedDirectedGraph # Create a directed graph using an adjacency list g = LinkedDirectedGraph() # Add vertices labeled A, B, and C to the graph and print it g.addVertex("A") g.addVertex("B") g.addVertex("C") print("Expect vertices ABC and no edges: \n" + str(g)) # Insert edges with weight 2.5 and print the graph g.addEdge("A", "B", 2.5) g.addEdge("B", "C", 2.5) g.addEdge("C", "B", 2.5) print("Expect same vertices and edges AB BC CB all with weight 2.5: \n" + str(g)) #g.addVertex("A") #g.addEdge("A", "D", 2.5)
if numSpaces <= 0: return data else: spacesLeft = numSpaces // 2 spacesRight = numSpaces // 2 if numSpaces % 2 == 1: spacesLeft += 1 return spacesLeft * " " + data + spacesRight * " " # Create a randomly ordered list of labels lyst = list("ABCDEFGHI") random.shuffle(lyst) # Create a graph with those vertex labels graph = LinkedDirectedGraph(lyst) # Create the label table for the graph table = graph.makeLabelTable() keys = list(table.keys()) keys.sort() # Add some edges with weights and print the graph for i in range(len(keys) - 1): graph.addEdge(keys[i], keys[i + 1], i) print("\nThe graph:") print(graph) # Create and print the labeled distance matrix matrix = graph.makeDistanceMatrix(table) print("\nThe initial labeled distance matrix:")
def createGraphFromFile(): """Creates a graph from a file. Returns the graph if it was successfully created or an error message otherwise.""" fileName = input("Enter the file name: ") theFile = open(fileName, 'r') graph = LinkedDirectedGraph() rep = theFile.read() edgeList = rep.split() for edge in edgeList: if not '>' in edge: # A disconnected vertex if not graph.containsVertex(edge): graph.addVertex(edge) else: graph = None return "Duplicate vertex" else: # Two vertices and an edge bracketPos = edge.find('>') colonPos = edge.find(':') if bracketPos == -1 or colonPos == -1 or \ bracketPos > colonPos: self._graph = None return "Problem with > or :" fromLabel = edge[:bracketPos] toLabel = edge[bracketPos + 1:colonPos] weight = edge[colonPos + 1:] if weight.isdigit(): weight = int(weight) if not graph.containsVertex(fromLabel): graph.addVertex(fromLabel) if not graph.containsVertex(toLabel): graph.addVertex(toLabel) if graph.containsEdge(fromLabel, toLabel): graph = None return "Duplicate edge" graph.addEdge(fromLabel, toLabel, weight) return graph
def main(): g = LinkedDirectedGraph() # Insert vertices g.addVertex("A") g.addVertex("B") g.addVertex("C") g.addVertex("D") g.addVertex("E") # Insert weighted edges g.addEdge("A", "B", 3) g.addEdge("A", "C", 2) g.addEdge("B", "D", 1) g.addEdge("C", "D", 1) g.addEdge("D", "E", 2) print("The graph:\n", g) for vertex in g.vertices(): label = vertex.getLabel() print("Path from B to " + label + ": " + str(hasPath(g, "B", label))) print("Path from B to X: " + str(hasPath(g, "B", "X")))
""" File: testdirected.py Project 12.7 Tests making a label table. """ from graph import LinkedDirectedGraph import random # Create a randomly ordered list of labels lyst = list(map(lambda label: "Label" + str(label), range(1, 10))) random.shuffle(lyst) print("The listof labels:\n", lyst) # Create and print a graph with those vertex labels graph = LinkedDirectedGraph(lyst) print("\nThe graph:\n", graph) # Create and print the label table for the graph table = graph.makeLabelTable() print("\nThe label table:") keys = list(table.keys()) keys.sort() for key in keys: print(table[key], key)
def topologicalSort(graph): # <your code> graph = LinkedDirectedGraph() # The graph represents the following course prerequisites: # A requires nothing # B requires nothing # C requires A # D requires A, B, and C # E requires C # F requires B and D # G requires E and F # H requires C, F, and G # Part 2: # Add the vertices: # <your code> graph.addVertex("A") graph.addVertex("B") graph.addVertex("C") graph.addVertex("D") graph.addVertex("E") graph.addVertex("F") graph.addVertex("G") graph.addVertex("H") # Part 3: # Add the edges: # <your code> graph.addEdge("A", "C", 0) graph.addEdge("A", "D", 0) graph.addEdge("B", "D", 0) graph.addEdge("C", "D", 0) graph.addEdge("C", "E", 0) graph.addEdge("B", "F", 0) graph.addEdge("D", "F", 0) graph.addEdge("E", "G", 0) graph.addEdge("F", "G", 0) graph.addEdge("C", "H", 0) graph.addEdge("F", "H", 0) graph.addEdge("G", "H", 0) print("Graph:") print(graph) print("Courses:") # Part 4: # Display each vertex on a separate line: # <your code> for vertex in graph.vertices(): print(str(vertex)) print() print("Prerequisites:") # Part 5: # Display each edge on a separate line: # <your code> for edge in graph.edges(): print(str(edge)) print("One possible order to take the courses:") # Part 6: # Display the courses in prerequisite (topological) order: # <your code> stack = [] for i in graph.vertices(): if not i.isMarked(): topologicalSortStack(i, stack) print(" ".join(str(x) for x in stack)) print()
""" File: testundirected.py """ from graph import LinkedDirectedGraph lyst = ["a", "b", "c", "d"] g = LinkedDirectedGraph(lyst) print("Expect 4 : " + str(g.sizeVertices())) print("Expect 4 vertices a b c d and no edges: " + str(g)) # Mark vertices, count marks, clear marks, count marks for vertex in g.vertices(): vertex.setMark() count = 0 for vertex in g.vertices(): if vertex.isMarked(): count += 1 print("Expect 4: " + str(count)) g.clearVertexMarks() count = 0 for vertex in g.vertices(): if vertex.isMarked(): count += 1 print("Expect 0: " + str(count)) # Insert some edges g.addEdge("a", "b", 1) g.addEdge("c", "d", 2) # Mark edges, count marks, clear marks, count marks for edge in g.edges():
class GraphDemoModel(object): """模型类""" def __init__(self): self._graph = None self._start_label = None def create_graph(self, rep, start_label): """创建图""" self._graph = LinkedDirectedGraph() self._start_label = start_label edge_list = rep.split() for edge in edge_list: if not '->' in edge: # 单个顶点(edge == label) if not self._graph.contain_vertex(edge): self._graph.add_vertex(edge) else: self._graph = None return "Duplicate vertex" else: # 两个顶点和一条边 bracket_pos = edge.find("->") col_on_pos = edge.find(":") if bracket_pos == -1 or col_on_pos == -1 or \ bracket_pos > col_on_pos: self._graph = None return "Problem with -> or :" from_label = edge[:bracket_pos] to_label = edge[bracket_pos + 2:col_on_pos] weight = edge[col_on_pos + 1:] if weight.isdigit(): weight = int(weight) if not self._graph.contain_vertex(from_label): self._graph.add_vertex(from_label) if not self._graph.contain_vertex(to_label): self._graph.add_vertex(to_label) if self._graph.contain_edge(from_label, to_label): self._graph = None return "Duplicate edge" self._graph.add_edge(from_label, to_label, weight) # 起始顶点 vertex = self._graph.get_vertex(start_label) if vertex == None: self._graph = None return "Start label not in graph" else: vertex.set_mark() return "Graph created successfully" def get_graph(self): """返回图""" if self._graph == None: return None else: return str(self._graph) def run(self, algorithm): """根据参数,运行指定的算法""" if self._graph == None: return None else: return algorithm(self._graph, self._start_label)