1)图的概念:
simple graph: 无向图 连个点只有一条边相连 每条边都连接不同的点
regular graph:每个点,连接相同的其余点。即
complete graph:每个点连接其他的所有点
tree, forest:A tree is a connected graph with no cycles.A forest is a graph with no cycles (i.e. the disjoint union of one or more trees).
2)__repr__ , __str__, represent 代表了 Python Expression str 方便人们阅读
3)用字典套字典的方法实现图,外层key的值是各个点,内层字典,就是每个点代表一个字典,他的key是与之相连的点的,value是二者之间的边
4)边的类型是Tuple
1 class Edge(tuple): 2 def __new__(cls, e1, e2): 3 return tuple.__new__(cls, (e1, e2)) 4 5 def __repr__(self): 6 return 'Ege(%s, %s)' % (repr(self[0]), repr(self[1])) 7 8 __str__ = __repr__
最后的
__str__ = __repr__
让输出保持一致,可以直接使用 print。
5)下边是点的实现,比较简单。
class Vertex(object): def __init__(self, label=''): self.label = label def __repr__(self): return 'Vertex(%s)' % repr(self.label) __str__ = __repr__
整个图的类型
class Graph(dict): """ A Graph is used by Python 3.3.2 """ def __init__(self, vs=[], es=[]): """create a new graph. (vs) is list of verticaes; (es) is a list of edges.""" for v in vs: self.add_vertex(v) for e in es: self.add_edge(e) def add_vertex(self, v): """add (v) to the graph""" self[v] = {} def add_edge(self, e): """add (e) to the graph by adding an entry in both directions. If there is already an edge connecting these Vertics, the new edge replaces it. """ v , w = e self[v][w] = e self[w][v] = e
整个图的类型就是我所说的字典套字典。
所以在提取边和点的时候,一定要注意类型。
内建在图内的方法,提取所有边。
def out_edges(self, v): t = [] try: for ed in self[v].values(): t.append(ed) return t except KeyError: return None
加入 try 为了让程序有更多的容错性。