python networkx pygraphviz简单使用

from heapq import *
import networkx as nx
import matplotlib.pyplot as plt
import pygraphviz as pgv

class Node:

    def __init__(self, label, weight):
        self.left = None
        self.right = None
        self.label = label
        self.weight = weight
    def __lt__(self, other):
        return self.weight < other.weight

    def __eq__(self, other):
        return self.weight == other.weight and self.label==other.label

    def __hash__(self):
        return hash(id(self))
    def __str__(self):
        return str(self.weight) if not self.label.startswith('N') else self.label+':'+str(self.weight)


def huffman(A):
    A=[Node(str(i),i)for i in A]
    cnt=1
    heapify(A)
    while len(A)>1:
            x=heappop(A);y=heappop(A)
            xy=Node('N'+str(cnt),x.weight+y.weight)
            xy.left=x;xy.right=y

            heappush(A,xy);cnt+=1
            if len(A)==1:
                A[0].label='Root'
                return heappop(A)

def mplt(A):
    T=nx.DiGraph()
    if  A is not None:
        cons(A,T)
    nx.draw(T, with_labels=True, font_weight='bold')

    G=pgv.AGraph(strict=True,directed=True)
    G.add_nodes_from(T.nodes())
    G.add_edges_from(T.edges())

    G.write("first.dot")


    G.layout(prog='dot')

    G.draw('/Users/hello/first.png')
    plt.show()

def cons(A,T):
    if  A is not None:
        if A.left is not None:
            T.add_edge(A,A.left)
            cons(A.left,T)
        if A.right is not None:
            T.add_edge(A,A.right)
            cons(A.right,T)

def visit(A):
    if  A is not None:
        print(A.label ,A.weight)
        visit(A.left)
        visit(A.right)
if __name__ == '__main__':
        A=[1,45,4,2,3,6,7,8,9,22,111,231]
        h_g=huffman(A)
        visit(h_g)
        mplt(h_g)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值