先從無加權(quán)圖開始但两,實(shí)現(xiàn)了插入頂點(diǎn)鬓梅、插入邊、刪除頂點(diǎn)谨湘、刪除邊的功能绽快。
建立Graph.py
#頂點(diǎn)類
class Vertex:
def __init__(self,name):
self.name = name
self.next = []
class Graph:
def __init__(self):
self.vertexList = {}
def addVertex(self,vertex):
if vertex in self.vertexList:
return
self.vertexList[vertex] = Vertex(vertex)
def addEdge(self,fromVertex,toVertex):
if fromVertex == toVertex:
return
if fromVertex not in self.vertexList:
print("vertexList has no ",fromVertex)
return
if toVertex not in self.vertexList:
print("vertexList has no ", toVertex)
return
if(toVertex not in self.vertexList[fromVertex].next):
self.vertexList[fromVertex].next.append(toVertex)
if (fromVertex not in self.vertexList[toVertex].next):
self.vertexList[toVertex].next.append(fromVertex)
# self.vertexList[fromVertex].next.append(toVertex)
# self.vertexList[toVertex].next.append(fromVertex)
def removeVertex(self,vertex):
if vertex in self.vertexList:
removed = self.vertexList.pop(vertex)
removed = removed.name
for key, vertex in self.vertexList.items():
if removed in vertex.next:
vertex.next.remove(removed)
def removeEdge(self,fromVertex,toVertex):
if fromVertex not in self.vertexList:
if fromVertex not in self.vertexList:
print("vertexList has no ", fromVertex)
return
if toVertex not in self.vertexList:
print("vertexList has no ", toVertex)
return
if fromVertex in self.vertexList[toVertex].next:
self.vertexList[fromVertex].next.remove(toVertex)
self.vertexList[toVertex].next.remove(fromVertex)
測試代碼,在Grapy.py同級目錄建立紧阔,test.py
import Graph
G = Graph.Graph()
for i in range(1,10):
G.addVertex(i)
for i in range(1,9):
G.addEdge(i,i+1)
G.addEdge(i,3)
G.addEdge(i,4)
G.removeVertex(3)
G.removeEdge(9,4)
for i,g in G.vertexList.items():
print(i,g.next)
輸出
1 [2, 4]
2 [1, 4]
4 [1, 2, 5, 6, 7, 8]
5 [4, 6]
6 [5, 7, 4]
7 [6, 8, 4]
8 [7, 9, 4]
9 [8]