python---使用字典来实现链接表图

最后一章,坚持!!!

python---使用字典来实现链接表图

python---使用字典来实现链接表图

# coding = utf-8


class Vertex:
    def __init__(self, key):
        self.id = key
        self.connected_to = {}

    def add_neighbor(self, nbr, weight=0):
        self.connected_to[nbr] = weight

    def __str__(self):
        return str(self.id) + ' connected to: ' + str([x.id for x in self.connected_to])

    def get_connections(self):
        return self.connected_to.keys()

    def get_id(self):
        return self.id

    def get_weight(self, nbr):
        return self.connected_to[nbr]


class Graph:
    def __init__(self):
        self.vertex_list = {}
        self.num_vertices = 0

    def add_vertex(self, key):
        self.num_vertices = self.num_vertices + 1
        new_vertex = Vertex(key)
        self.vertex_list[key] = new_vertex
        return new_vertex

    def get_vertex(self, n):
        if n in self.vertex_list:
            return self.vertex_list[n]
        else:
            return None

    def __contains__(self, item):
        return item in self.vertex_list

    def add_edge(self, f, t, cost=0):
        if f not  in self.vertex_list:
            nv = self.add_vertex(f)
        if t not in self.vertex_list:
            nv = self.add_vertex(t)
        self.vertex_list[f].add_neighbor(self.vertex_list[t], cost)

    def get_vertices(self):
        return self.vertex_list.keys()

    def __iter__(self):
        return iter(self.vertex_list.values())


g = Graph()
for i in range(6):
    g.add_vertex(i)
print(g.vertex_list)
g.add_edge(0, 1, 5)
g.add_edge(0, 5, 2)
g.add_edge(1, 2, 4)
g.add_edge(2, 3, 9)
g.add_edge(3, 4, 7)
g.add_edge(3, 5, 3)
g.add_edge(4, 0, 1)
g.add_edge(5, 4, 8)
g.add_edge(5, 2, 1)

for v in g:
    for w in v.get_connections():
        print("( %s, %s )" % (v.get_id(), w.get_id()))

 

C:\Users\Sahara\.virtualenvs\test\Scripts\python.exe C:/Users/Sahara/PycharmProjects/test/python_search.py
{0: <__main__.Vertex object at 0x0000000001E83DA0>, 1: <__main__.Vertex object at 0x0000000001E83DD8>, 2: <__main__.Vertex object at 0x0000000001E83E10>, 3: <__main__.Vertex object at 0x0000000001E83E48>, 4: <__main__.Vertex object at 0x0000000001E83E80>, 5: <__main__.Vertex object at 0x0000000001E83EB8>}
( 0, 1 )
( 0, 5 )
( 1, 2 )
( 2, 3 )
( 3, 4 )
( 3, 5 )
( 4, 0 )
( 5, 4 )
( 5, 2 )

Process finished with exit code 0

  

上一篇:ANSYS ICEM CFD三维结构网格生成实例——汽车外流


下一篇:深度优先搜索(BFS)和广度优先搜索( DFS)还有 迪杰斯特拉算法(dijkstra)