首页 / PYTHON / Python_自定义有向图
Python_自定义有向图
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python_自定义有向图,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1406字,纯文字阅读大概需要3分钟。
内容图文
![Python_自定义有向图](/upload/InfoBanner/zyjiaocheng/1135/413a1c45df474422bcb96d4f68781ae7.jpg)
directedGraph.py
1 class DirectedGraph(object): 2 def __init__ (self,d): 3 if isinstance(d,dict): 4 self.__graph = d 5else: 6 self.__graph = dict() 7print(‘Sth error‘) 8 9def__generatePath(self,graph,path,end,results): 10 curret = path[-1] 11if curret == end: 12 results.append(path) 13else: 14for n in graph[curret]: 15if n notin path: 16 self.__generatePath(graph,path+[n],end,results) 1718def searchPath(self,start,end): 19 self.__results = [] 20 self.__generatePath(self.__graph,[start],end,self.__results) 21 self.__results.sort(key=lambda x:len(x)) #按所有路径的长度进行排序22print(‘The path from ‘,self.__results[0][0],‘to‘,self.__results[0][-1],‘is:‘) 23for path in self.__results: 24print(path) 25 d={‘A‘:[‘B‘,‘C‘,‘D‘], 26‘B‘:[‘E‘], 27‘C‘:[‘D‘,‘F‘], 28‘D‘:[‘B‘,‘E‘,‘G‘], 29‘E‘:[‘D‘], 30‘F‘:[‘D‘,‘G‘], 31‘G‘:[‘E‘]} 32 g=DirectedGraph(d) 33 g.searchPath(‘A‘,‘D‘) 34 g.searchPath(‘A‘,‘E‘) 3536‘‘‘输出结果37The path from A to D is: 38[‘A‘, ‘D‘] 39[‘A‘, ‘C‘, ‘D‘] 40[‘A‘, ‘B‘, ‘E‘, ‘D‘] 41[‘A‘, ‘C‘, ‘F‘, ‘D‘] 42[‘A‘, ‘C‘, ‘F‘, ‘G‘, ‘E‘, ‘D‘] 43The path from A to E is: 44[‘A‘, ‘B‘, ‘E‘] 45[‘A‘, ‘D‘, ‘E‘] 46[‘A‘, ‘C‘, ‘D‘, ‘E‘] 47[‘A‘, ‘D‘, ‘B‘, ‘E‘] 48[‘A‘, ‘D‘, ‘G‘, ‘E‘] 49[‘A‘, ‘C‘, ‘D‘, ‘B‘, ‘E‘] 50[‘A‘, ‘C‘, ‘D‘, ‘G‘, ‘E‘] 51[‘A‘, ‘C‘, ‘F‘, ‘D‘, ‘E‘] 52[‘A‘, ‘C‘, ‘F‘, ‘G‘, ‘E‘] 53[‘A‘, ‘C‘, ‘F‘, ‘D‘, ‘B‘, ‘E‘] 54[‘A‘, ‘C‘, ‘F‘, ‘D‘, ‘G‘, ‘E‘] 55‘‘‘
原文:http://www.cnblogs.com/cmnz/p/6937944.html
内容总结
以上是互联网集市为您收集整理的Python_自定义有向图全部内容,希望文章能够帮你解决Python_自定义有向图所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。