在Python中使用 Dictionary 生成图形
先决条件 - 图表
使用内置库绘制图形 – Python中的图形绘图
在本文中,我们将看到如何在Python中使用字典数据结构在Python中实现图形。
使用的字典的键是我们图的节点,对应的值是每个节点的列表,它们通过一条边连接。
这个简单的图有六个节点 (af) 和五个弧:
a -> c
b -> c
b -> e
c -> a
c -> b
c -> d
c -> e
d -> c
e -> c
e -> b
它可以用下面的Python数据结构来表示。这是一个字典,其键是图的节点。对于每个键,对应的值是一个列表,其中包含通过该节点的直接弧连接的节点。
graph = { "a" : ["c"],
"b" : ["c", "e"],
"c" : ["a", "b", "d", "e"],
"d" : ["c"],
"e" : ["c", "b"],
"f" : []
}
上述示例的图形表示:
defaultdict:通常,如果您尝试使用当前不在字典中的键获取项目, Python字典会抛出 KeyError。 defaultdict 允许如果在字典中找不到键,则不会抛出 KeyError,而是创建一个新条目。这个新条目的类型由 defaultdict 的参数给出。
生成图形的Python函数:
# definition of function
def generate_edges(graph):
edges = []
# for each node in graph
for node in graph:
# for each neighbour node of a single node
for neighbour in graph[node]:
# if edge exists then append
edges.append((node, neighbour))
return edges
Python3
# Python program for
# validation of a graph
# import dictionary for graph
from collections import defaultdict
# function for adding edge to graph
graph = defaultdict(list)
def addEdge(graph,u,v):
graph[u].append(v)
# definition of function
def generate_edges(graph):
edges = []
# for each node in graph
for node in graph:
# for each neighbour node of a single node
for neighbour in graph[node]:
# if edge exists then append
edges.append((node, neighbour))
return edges
# declaration of graph as dictionary
addEdge(graph,'a','c')
addEdge(graph,'b','c')
addEdge(graph,'b','e')
addEdge(graph,'c','d')
addEdge(graph,'c','e')
addEdge(graph,'c','a')
addEdge(graph,'c','b')
addEdge(graph,'e','b')
addEdge(graph,'d','c')
addEdge(graph,'e','c')
# Driver Function call
# to print generated graph
print(generate_edges(graph))
Python3
# Python program to generate the first
# path of the graph from the nodes provided
graph = {
'a': ['c'],
'b': ['d'],
'c': ['e'],
'd': ['a', 'd'],
'e': ['b', 'c']
}
# function to find path
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath:
return newpath
# Driver function call to print the path
print(find_path(graph, 'd', 'c'))
Python3
# Python program to generate the all possible
# path of the graph from the nodes provided
graph ={
'a':['c'],
'b':['d'],
'c':['e'],
'd':['a', 'd'],
'e':['b', 'c']
}
# function to generate all possible paths
def find_all_paths(graph, start, end, path =[]):
path = path + [start]
if start == end:
return [path]
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
# Driver function call to print all
# generated paths
print(find_all_paths(graph, 'd', 'c'))
Python3
# Python program to generate shortest path
graph ={
'a':['c'],
'b':['d'],
'c':['e'],
'd':['a', 'd'],
'e':['b', 'c']
}
# function to find the shortest path
def find_shortest_path(graph, start, end, path =[]):
path = path + [start]
if start == end:
return path
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
# Driver function call to print
# the shortest path
print(find_shortest_path(graph, 'd', 'c'))
输出:
[('a', 'c'), ('c', 'd'), ('c', 'e'), ('c', 'a'), ('c', 'b'),
('b', 'c'), ('b', 'e'), ('e', 'b'), ('e', 'c'), ('d', 'c')]
正如我们以无向图为例,所以我们两次打印相同的边,分别为 ('a','c') 和 ('c','a')。我们可以通过使用有向图来克服这个问题。
下面是一些关于Python图形的更多程序:要生成从一个节点到另一节点的路径:
使用Python字典,我们可以在图中找到从一个节点到另一个节点的路径。这个想法类似于图中的 DFS。
在函数中,最初,路径是一个空列表。在开始时,如果开始节点与结束节点匹配,则函数将返回路径。否则,代码继续前进并命中起始节点的所有值并使用递归搜索路径。
Python3
# Python program to generate the first
# path of the graph from the nodes provided
graph = {
'a': ['c'],
'b': ['d'],
'c': ['e'],
'd': ['a', 'd'],
'e': ['b', 'c']
}
# function to find path
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath:
return newpath
# Driver function call to print the path
print(find_path(graph, 'd', 'c'))
输出:
['d', 'a', 'c']
生成从一个节点到另一个节点的所有可能路径的程序。 :
在上面讨论的程序中,我们生成了第一个可能的路径。现在,让我们生成从开始节点到结束节点的所有可能路径。基本功能与上述代码的功能相同。不同之处在于它不是立即返回第一个路径,而是将该路径保存在名为“路径”的列表中,如下例所示。最后,在遍历所有可能的方式之后,它返回路径列表。如果没有从起始节点到结束节点的路径,则返回 None。
Python3
# Python program to generate the all possible
# path of the graph from the nodes provided
graph ={
'a':['c'],
'b':['d'],
'c':['e'],
'd':['a', 'd'],
'e':['b', 'c']
}
# function to generate all possible paths
def find_all_paths(graph, start, end, path =[]):
path = path + [start]
if start == end:
return [path]
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
# Driver function call to print all
# generated paths
print(find_all_paths(graph, 'd', 'c'))
输出:
[['d', 'a', 'c'], ['d', 'a', 'c']]
生成最短路径的程序。 :
为了从所有路径中获得最短路径,我们使用了一些不同的方法,如下所示。在此,当我们获得从开始节点到结束节点的路径时,我们将路径的长度与名为 shortest 的变量进行比较,该变量用 None 值初始化。如果生成路径的长度小于shortest的长度,如果shortest不是None,则将新生成的路径设置为shortest的值。同样,如果没有路径,则返回 None
Python3
# Python program to generate shortest path
graph ={
'a':['c'],
'b':['d'],
'c':['e'],
'd':['a', 'd'],
'e':['b', 'c']
}
# function to find the shortest path
def find_shortest_path(graph, start, end, path =[]):
path = path + [start]
if start == end:
return path
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
# Driver function call to print
# the shortest path
print(find_shortest_path(graph, 'd', 'c'))
输出:
['d', 'a', 'c']