python数据结构之图的实现方法

yipeiwu_com5年前Python基础

本文实例讲述了python数据结构之图的实现方法。分享给大家供大家参考。具体如下:

下面简要的介绍下:

比如有这么一张图:

    A -> B
    A -> C
    B -> C
    B -> D
    C -> D
    D -> C
    E -> F
    F -> C

可以用字典和列表来构建

graph = {'A': ['B', 'C'],
       'B': ['C', 'D'],
       'C': ['D'],
       'D': ['C'],
       'E': ['F'],
       'F': ['C']}

找到一条路径:

def find_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
      return path
    if not graph.has_key(start):
      return None
    for node in graph[start]:
      if node not in path:
        newpath = find_path(graph, node, end, path)
        if newpath: return newpath
    return None

找到所有路径:

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
      return [path]
    if not graph.has_key(start):
      return []
    paths = []
    for node in graph[start]:
      if node not in path:
        newpaths = find_all_paths(graph, node, end, path)
        for newpath in newpaths:
          paths.append(newpath)
    return paths

找到最短路径:

def find_shortest_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
      return path
    if not graph.has_key(start):
      return None
    shortest = None
    for node in graph[start]:
      if node not in path:
        newpath = find_shortest_path(graph, node, end, path)
        if newpath:
          if not shortest or len(newpath) < len(shortest):
            shortest = newpath
    return shortest

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python基础教程之分支、循环简单用法

本文实例讲述了python分支、循环简单用法。分享给大家供大家参考,具体如下: 讲程序设计,不得不讲到顺序、分支、循环。 顺序就是从上到下运行代码,这个很简单,不用再说了。 在讲分支、循...

跟老齐学Python之编写类之一创建实例

说明:关于类的这部分,我参考了《Learning Python》一书的讲解。 创建类 创建类的方法比较简单,如下: 复制代码 代码如下: class Person:  注意,...

Python 数值区间处理_对interval 库的快速入门详解

使用 Python 进行数据处理的时候,常常会遇到判断一个数是否在一个区间内的操作。我们可以使用 if else 进行判断,但是,既然使用了 Python,那我们当然是想找一下有没有现成...

详解Python 定时框架 Apscheduler原理及安装过程

详解Python 定时框架 Apscheduler原理及安装过程

在我们的日常工作自动化测试当中,几乎超过一半的功能都需要利用定时的任务来推动触发,例如在我们项目中有一个定时监控模块,根据自己设置的频率定时跑测试用例,定时检测是否存在线上紧急任务等等,...

使用Python将Mysql的查询数据导出到文件的方法

mysql官方提供了很多种connector,其中包括python的connector。 下载地址在:http://dev.mysql.com/downloads/connector/p...