python使用邻接表实现图

Source
# -*- coding: utf-8 -*-

class Vertex:
    
    def __init__(self,id):
        self.id=id
        self.connect_to={
    
      }
        
    def add_neighbor(self,nbr_id,weight=0):
        self.connect_to[nbr_id]=weight
        
    def get_connections(self):
        return self.connect_to.keys()
    
    def get_id(self):
        return self.id
    
    def get_weight(self,nbr_id):
        return self.connect_to[nbr_id]
    
    def __str__(self):
        return str(self.id)+' connect to '+str([x.id for x in self.connect_to])
    
class Graph:
    
    def __init__(self):
        self.vert_list={
    
      }
        self.num_vertices=0
        
    def add_vertex(self,id):
        self.num_vertices+=1
        new_vert=Vertex(id)
        self.vert_list[id]=new_vert
        return new_vert
    
    def get_vertex(self,id):
        if id in self.vert_list:
            return self.vert_list[id]
        else:
            return None
        
    def add_edge(self,from_,to,weight=0):
        if from_ not in self.vert_list:
            new_vertex=self.add_vertex(from_)
        if to not in self.vert_list:
            new_vertex=self.add_vertex(to)
        
        self.vert_list[from_].add_neighbor(self.vert_list[to],weight)
        
    def get_all_vertices(self):
        return self.vert_list.keys()
    
    def __contains__(self,id):
        return id in self.vert_list
    
    def __iter__(self):
        return iter(self.vert_list.values())
        
    
if __name__=="__main__":
    
    g=Graph()
    print(g)
    for i in range(6):
        g.add_vertex(i)
    print(g.vert_list)
    g.add_edge(0,1,1)
    g.add_edge(0,2,2)
    g.add_edge(0,3,3)
    print(g.get_all_vertices())
    print(g.vert_list[0])
    for i in range(6):
        print(g.vert_list[i])
    for v in g:
        print('v=',v)
        for w in v.get_connections():
            print('w=',w)
            print("({},{})".format(v.get_id(),w.get_id()))