The Graph
Abstract Data Type describes a strategy for using Vertex
objects to describe a Graph.
The Vertex
class describes the nodes in the graph. Its ADT includes:
Vertex(key)
- creates a new vertex with a given keyaddNeighbor(neighborVertex, weight)
- creates a connection of the specified weight to another vertexgetConnections()
- identifies all of the vertices this one is connected togetID()
- returns the key for this vertexgetWeight(neighborVertex)
= identifies the weight of the edge between this vertex and the specified neighborUse the following code as a template for writing the Vertex
class.
class Vertex(object):
"""Describes a vertex object in terms of a "key" and a
dictionary that indicates edges to neighboring vertices with
a specified weight.
"""
def __init__(self, key):
"""Constructs a vertex with a key value and an empty dictionary
"connected_to" where we'll store other vertices to which this vertex is connected.
"""
def add_neighbor(self, neighbor_vertex, weight=0):
"""Adds a reference to a neighboring Vertex object to the dictionary,
to which this vertex is connected by an edge. If a weight is not indicated,
default weight is 0.
"""
def __repr__(self):
"""Returns a representation of the vertex and its neighbors,
suitable for printing. Check out the example of
'list comprehension' here!
"""
return str(self.id) + ' connected_to: ' + str([x.id for x in self.connected_to])
def get_connections(self):
"""Returns the keys of the vertices we're connected to
"""
def get_id(self):
"""Returns the id ("key") for this vertex
"""
def get_weight(self, neighbor_vertex):
"""Returns the weight of an edge connecting this vertex with another.
"""
You can test your class by running the following commands:
v1 = Vertex(1)
v2 = Vertex(2)
v3 = Vertex(3)
v1.add_neighbor(v2)
v1.add_neighbor(v3,7)
print("Vertex v1 is ", v1)
print("Vertex v1 is connected to ", v1.get_connections())
print("The weight between v1 and v3 is ", v1.get_weight(v3))
print("Vertex v2 is connected to ", v2.get_connections())
Expected output similar to:
Vertex v1 is 1 connected to: [2, 3]
Vertex v1 is connected to dict_keys([<__main__.Vertex object at 0x7f85981cca90>, <__main__.Vertex object at 0x7f85981a2370>])
The weight between v1 and v3 is 7
Vertex v2 is connected to dict_keys([])