python 实现Graph class

来源:互联网 发布:云交易软件 编辑:程序博客网 时间:2024/06/05 17:45

Today, I wrote a class Graph in python, for the purpose of implementing the following dfs and bfs:

Can use the tinyG.txt for input.

class Graph():    def __init__(self, filepath):        self.V = 0  #-- num of vertices        self.E = 0  #-- num of edges        self.adj = {}        self.filepath = filepath        fhand = open(self.filepath)                self.V = int(fhand.readline())        self.E = int(fhand.readline())                for i in range(0, self.E):            string = fhand.readline()            string = string.split(' ')        ''' the two vertices was seperated by ' '. '''            v = int(string[0])            w = int(string[1])                    '''if vertices was not created yet,'''        '''have to create a empty list for that vertice'''                    if v not in self.adj:                                self.adj[v] = []                            if w not in self.adj:                self.adj[w] = []                        self.addEdge(v, w)            def __str__(self):        s = ''        for item in self.adj:            s = s + str(item) + ':' + str(self.adj[item]) + '\n'        return s        #return str(self.adj)    def addEdge(self, v , w):        self.adj[v].append(w)        self.adj[w].append(v)        self.E += 1    def get_Vertivces():        return self.Vdef main():    filename = raw_input('please input file name: ')    g = Graph(filename)    print gmain()


0 0
原创粉丝点击