python,从最底层开始手撸图论算法(一)

先从无加权图开始,实现了插入顶点、插入边、删除顶点、删除边的功能。
建立Graph.py

#顶点类
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]

你可能感兴趣的:(python,从最底层开始手撸图论算法(一))