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 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")))
for edge in g.edges(): if edge.isMarked(): count += 1 print("Expect 2: " + str(count)) g.clearEdgeMarks() count = 0; for edge in g.edges(): if edge.isMarked(): count += 1 print("Expect 0: " + str(count)) # Clear graph g.clear() # Insert vertices g.addVertex("a") g.addVertex("b") g.addVertex("c") g.addVertex("d") g.addVertex("e") g.addVertex("f") g.addVertex("g") g.addVertex("h") g.addVertex("i") g.addVertex("j") # Test some vertex methods result = "" for vertex in g.vertices(): result += str(vertex) + " " print("Expect 10 :", g.sizeVertices())
""" 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)
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)
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) chart.addEdge("CSCI112", "CSCI209", 1) chart.addEdge("CSCI112", "CSCI211", 1) chart.addEdge("CSCI112", "CSCI312", 1) chart.addEdge("MATH121", "CSCI211", 1) chart.addEdge("MATH121", "MATH102", 1) chart.addEdge("MATH121", "MATH122", 1) chart.addEdge("MATH121", "CSCI313", 1) chart.addEdge("MATH121", "CSCI312", 1)
""" 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
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) chart.addEdge("CSCI112", "CSCI209", 1) chart.addEdge("CSCI112", "CSCI211", 1) chart.addEdge("CSCI112", "CSCI312", 1) chart.addEdge("MATH121", "CSCI211", 1) chart.addEdge("MATH121", "MATH102", 1) chart.addEdge("MATH121", "MATH122", 1) chart.addEdge("MATH121", "CSCI313", 1) chart.addEdge("MATH121", "CSCI312", 1)
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()