Bar*_*raa 12 python algorithm adjacency-list adjacency-matrix
你好,我理解邻接列表和矩阵的概念,但我很困惑如何在Python中实现它们:
实现以下两个示例的算法实现但不知道从一开始的输入,因为他们在他们的示例中对其进行硬编码:
对于邻接列表:
a, b, c, d, e, f, g, h = range(8)
N = [
{b:2, c:1, d:3, e:9, f:4}, # a
{c:4, e:3}, # b
{d:8}, # c
{e:7}, # d
{f:5}, # e
{c:2, g:2, h:2}, # f
{f:1, h:6}, # g
{f:9, g:8} # h
]
Run Code Online (Sandbox Code Playgroud)
对于邻接矩阵:
a, b, c, d, e, f, g, h = range(8)
_ = float('inf')
# a b c d e f g h
W = [[0,2,1,3,9,4,_,_], # a
[_,0,4,_,3,_,_,_], # b
[_,_,0,8,_,_,_,_], # c
[_,_,_,0,7,_,_,_], # d
[_,_,_,_,0,5,_,_], # e
[_,_,2,_,_,0,2,2], # f
[_,_,_,_,_,1,0,6], # g
[_,_,_,_,_,9,8,0]] # h
Run Code Online (Sandbox Code Playgroud)
再次感谢任何帮助,谢谢!
假设:
edges = [('a', 'b'), ('a', 'b'), ('a', 'c')]
Run Code Online (Sandbox Code Playgroud)
这是矩阵的一些代码:
from collections import defaultdict
matrix = defaultdict(int)
for edge in edges:
matrix[edge] += 1
print matrix['a', 'b']
Run Code Online (Sandbox Code Playgroud)
2
Run Code Online (Sandbox Code Playgroud)
而对于"清单":
from collections import defaultdict
adj_list = defaultdict(lambda: defaultdict(lambda: 0))
for start, end in edges:
adj_list[start][end] += 1
print adj_list['a']
Run Code Online (Sandbox Code Playgroud)
{'c': 1, 'b': 2}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
23245 次 |
最近记录: |