操作图形的包
graphpython的Python项目详细描述
图形
这是一个处理图形的包 为巴西大学“巴拉那州联邦技术大学”的一类图表制作。
安装
pip install graphpython
完整文档
图表
要使用这个类,主要元素是Graph class
。使用这个类,您将能够用顶点和边填充图形,并执行所有必要的操作
Graph([directed])
:创建一个图directed
:默认为false。 指示图形是否有方向性
代码示例
# Create a new graphfromgraphpy.graphimportGraphgp=Graph()# add a new vertexgp.add_vertex('vertex1')# to get the create vertex, you can use the [] operatorvertex1=gp['vertex1']
顶点运算
所有图形的基是顶点,要创建新的顶点,必须使用以下函数
gp.add_vertex(name, [value])
:创建一个新顶点并插入到图中name
:图中顶点的唯一标识value
:顶点的可选值
gp.get_vertex(name)
或gp[name]
:从图返回顶点name
:图中顶点的唯一标识
gp.get_all_vertex()
:从图中获取包含所有顶点的列表gp.adjacents_vertex(vtx)
:从一个顶点获取所有相邻顶点vtx
:要知道相邻顶点的顶点
gp.remove_vertex(vertex_to_remove)
:删除一个顶点及其所有连接vertex_to_remove
:要移除的顶点
代码示例
fromgraphpy.graphimportGraphgp=Graph()gp.add_vertex('01')gp.remove_vertex(gp['01'])
在图中搜索
main类有一个搜索方法,要使用它,需要向by params传递一个进行搜索的策略。
实施新的搜索策略
课堂上已经实施了两种课堂策略:
- bfsstrategy
- DFSStrategy
fromgraphpy.graphimportGraphfromgraphpy.BFSstrategyimportBFSstrategygraph=Graph()graph.search(BFSstrategy(INITIAL_VERTEX))
要扩展所有搜索类型,您可以创建一个新策略,从search_strategy扩展searchstrategy类。
fromgraphpy.search_strategyimportSearchStrategyclassDFSstrategy(SearchStrategy):def__init__(self):self.__predecessors={}self.__firstSee={}self.__close={}self.__time=0def__dfs_visit(self,vertex):self.__time=self.__time+1self.__firstSee[vertex]=self.__timevertex.set_color(1)foradjacentinself.get_adjacent_list()[vertex]:ifadjacent.get_color()==0:self.__predecessors[adjacent]=vertexself.__dfs_visit(adjacent)vertex.set_color(2)self.__time+=1self.__close[vertex]=self.__timedefsearch(self):# colors:# white: not visited# grey: in the queue# black: nothing more to doforkeyinself.get_adjacent_list():# set color for all vertices to whitekey.set_color(0)self.__predecessors[key]=Noneself.__time=0forkeyinself.get_adjacent_list():ifkey.get_color()==0:self.__dfs_visit(key)returnself.__firstSee,self.__close,self.__predecessors