Beispiel #1
0
 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)
Beispiel #2
0
 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")
Beispiel #3
0
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
Beispiel #4
0
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")))
Beispiel #5
0
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():
    edge.setMark();
count = 0;
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
Beispiel #6
0
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)
Beispiel #7
0
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)
Beispiel #8
0
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)

# Print the edges of vertex B
# 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)

print("The chart: \n" + str(chart))

# Print the vertices adjacent to vertex CSCI112.
v = chart.getVertex("CSCI112")
Beispiel #10
0
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
Beispiel #11
0
"""
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)
Beispiel #12
0
# 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)

print("The chart: \n" + str(chart))

# Print the vertices adjacent to vertex CSCI112.
v = chart.getVertex("CSCI112")
Beispiel #13
0
# 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:")
printDistanceMatrix(matrix, table)

# Run Floyd's algorithm on the distance matrix
allPairsShortestPaths(matrix)

# Print the labeled matrix again
print("\nThe labeled distance matrix will all pairs shortest paths:")
printDistanceMatrix(matrix, table)
Beispiel #14
0
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)
Beispiel #15
0
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()