python數(shù)據(jù)結構之圖的實現(xiàn)方法
本文實例講述了python數(shù)據(jù)結構之圖的實現(xiàn)方法。分享給大家供大家參考。具體如下:
下面簡要的介紹下:
比如有這么一張圖:
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基于pywinauto實現(xiàn)的自動化采集任務
這篇文章主要介紹了Python基于pywinauto實現(xiàn)的自動化采集任務,模擬了輸入單詞, 復制例句, 獲取例句, 清空剪切板, 然后重復這個操作,需要的朋友可以參考下2023-04-04
Python使用Holoviews創(chuàng)建復雜的可視化布局
Holoviews是一個基于Python的開源庫,旨在簡化數(shù)據(jù)可視化的創(chuàng)建過程,本文將為新手朋友詳細介紹如何使用Holoviews創(chuàng)建復雜的可視化布局,感興趣的可以了解下2024-11-11
python庫Celery異步發(fā)送電子郵件定時生成報告實戰(zhàn)示例
這篇文章主要介紹了python庫Celery異步發(fā)送電子郵件定時生成報告實戰(zhàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
python獲取一組數(shù)據(jù)里最大值max函數(shù)用法實例
這篇文章主要介紹了python獲取一組數(shù)據(jù)里最大值max函數(shù)用法,實例分析了max函數(shù)的使用技巧,需要的朋友可以參考下2015-05-05
pymongo實現(xiàn)控制mongodb中數(shù)字字段做加法的方法
這篇文章主要介紹了pymongo實現(xiàn)控制mongodb中數(shù)字字段做加法的方法,涉及Python使用pymongo模塊操作mongodb數(shù)據(jù)庫字段的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03
如何使用Selenium實現(xiàn)簡單的網(wǎng)絡自動化操作指南
Selenium是一個用于Web應用測試的工具,Selenium測試直接運行在瀏覽器中,就像真正的用戶在操作一樣,這篇文章主要給大家介紹了關于如何使用Selenium實現(xiàn)簡單的網(wǎng)絡自動化操作的相關資料,需要的朋友可以參考下2024-03-03

