图:python实现

1)图的概念:
simple graph: 无向图 连个点只有一条边相连 每条边都连接不同的点
regular graph:每个点,连接相同的其余点。即
complete graph:每个点连接其他的所有点
tree, forest:A tree is a connected graph with no cycles.A forest is a graph with no cycles (i.e. the disjoint union of one or more trees).
2)__repr__ , __str__, represent 代表了 Python Expression str 方便人们阅读
3)用字典套字典的方法实现图,外层key的值是各个点,内层字典,就是每个点代表一个字典,他的key是与之相连的点的,value是二者之间的边
4)边的类型是Tuple

1 class Edge(tuple):
2     def __new__(cls, e1, e2):
3         return tuple.__new__(cls, (e1, e2))
4 
5     def __repr__(self):
6         return 'Ege(%s, %s)' % (repr(self[0]), repr(self[1]))
7 
8     __str__ = __repr__

最后的 

__str__ = __repr__

让输出保持一致,可以直接使用 print。

5)下边是点的实现,比较简单。

class Vertex(object):
    def __init__(self, label=''):
        self.label = label

    def __repr__(self):
        return 'Vertex(%s)' % repr(self.label)

    __str__ = __repr__

整个图的类型

class Graph(dict):
    """
    A Graph is used by Python 3.3.2
    """

    def __init__(self, vs=[], es=[]):
        """create a new graph. (vs) is list of verticaes;
        (es) is a list of edges."""
        for v in vs:
            self.add_vertex(v)

        for e in es:
            self.add_edge(e)

    def add_vertex(self, v):
        """add (v) to the graph"""
        self[v] = {}

    def add_edge(self, e):
        """add (e) to the graph by adding an entry in both directions.
        If there is already an edge connecting these Vertics, the new
        edge replaces it.
        """
        v , w = e
        self[v][w] = e
        self[w][v] = e

整个图的类型就是我所说的字典套字典。

所以在提取边和点的时候,一定要注意类型。

内建在图内的方法,提取所有边。

    def out_edges(self, v):
        t = []
        try:
            for ed in self[v].values():
              t.append(ed)
            return t
        except KeyError:
            return None

加入 try 为了让程序有更多的容错性。

转载于:https://www.cnblogs.com/svinlearnpy/p/3670093.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值