Feb 21
homework
Several folks had trouble with the code for the sorting algorithms.
Look at and discuss my examples of mergesort and quicksort :
sorting
Homework for the next two weeks, including the midterm, is posted.
graph code
As a class exercise, write Python code that
implements the storage and manipulation of graphs,
as we started to describe last class.
Here's a possible API
g = Graph(optional_properties)
g.add_edge(("vertex_name_1", "vertex_name_2")) # edge is a pair of strings
g.vertices() # return list of vertices (each is a string)
g.edges() # return list of edges (each is a pair of strings)
g.search("starting node", breadth_or_depth, function_to_apply)
This can be done with either adjacency_list or adjacency_matrix
internal storage of the graphs. (Perhaps that should be an option?
How can we transform one representation to the other? What
is the O() of that operation?)
Using it on the graph in the picture could be something like this :
g = Graph()
for edge in [('a', 'b'), ('a', 'c'), ('a', 'd'),
('b', 'c'), ('b', 'e'), ('c', 'd')]:
g.add_edge(edge)
print g.edges() # ['a', 'b', 'c', 'd', 'e']
def print_vertex(v):
print v
g.search('a', 'depth', print_vertex)
... which should print the order that we see the vertices
in a depth_first search starting at 'a'.
For the search, use the "fringe" and "queue or stack" approach,
along with independent implementations of those data structures :
s = Stack() # first in, last out
s.push("string")
"string" = s.pop()
q = Queue() # first in, first out
q.push("string")
"string = q.pop()
in class
This is as far as we got.
We decided to implement the graph
using an adjacency matrix, and
to make life simple by pre-allocating
a 100x100 matrix.
class Graph(object):
""" I'm a graph! """
# undirected graph
# simple graph (no a--a links; only one a--b same as b--a)
def __init__(self): # a -- b
self.max_size = 100
# make a big matrix.
# Don't do ([0]*n)*n ; that makes n copies of same list.
# 0 => not connected
# >=1 => connected with that weight
n = self.max_size
self.adj_matrix = [[0]*n for i in range(n)]
# grow list of vertices as needed
self.vertices = []
def has_vertex(self, string):
""" Return true if that vertex is in the graph """
return string in self.vertices
def add_vertex(self, string):
""" Modify the data structures to include this one """
if not self.has_vertex(string):
self.vertices.append(string)
def index(self, string):
""" Return index of given vertex name """
if self.has_vertex(string):
return self.vertices.index(string)
else:
return None
def add_edge(self, edge):
for v in edge:
self.add_vertex(v)
i = self.index(edge[0])
j = self.index(edge[1])
self.adj_matrix[i][j] = 1
self.adj_matrix[j][i] = 1