【问题标题】:Adjacency List and Adjacency Matrix in PythonPython中的邻接表和邻接矩阵
【发布时间】:2012-11-12 21:13:06
【问题描述】:

您好,我了解邻接表和矩阵的概念,但我对如何在 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 
   ] 

对于邻接矩阵:

    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

再次感谢任何帮助,谢谢!

【问题讨论】:

  • “不知道输入”
  • 例如我知道为了创建邻接列表或矩阵会有一个输入,但我不知道输入是什么,所以基本上是为了有一个每当我输入顶点和边以创建邻接列表或矩阵时的算法...
  • 邻接矩阵中的无穷大代表什么?
  • 这只是一个例子,它相当于一个缺失边的无穷大,你可以忽略它,认为它代表没有边。
  • 好的,那么 0 代表什么?对我来说,你似乎把它们弄错了。

标签: python algorithm adjacency-list adjacency-matrix


【解决方案1】:

假设:

edges = [('a', 'b'), ('a', 'b'), ('a', 'c')]

这是矩阵的一些代码:

from collections import defaultdict

matrix = defaultdict(int)
for edge in edges:
    matrix[edge] += 1

print matrix['a', 'b']
2

对于“列表”:

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']
{'c': 1, 'b': 2}

【讨论】:

  • 你们中的两个人提到了 defaultdict,由于我是 Python 新手,我不确定这到底意味着什么,愿意分享一些输入吗?感谢您提供的示例,尽管它们会有所帮助!
  • @user1748026 defaultdict 类型就像字典一样工作,但在设置时为它提供了“工厂功能”。然后,如果您访问一个不存在的键,它将调用工厂函数为该键创建一个默认值。
  • @Eric:我喜欢你的基于元组索引的矩阵解决方案。对于列表版本,您可以使用 int 作为内部 defaultdict 的工厂函数,而不是另一个 lambda 函数。
【解决方案2】:

设置数据结构非常简单。例如,邻接列表示例可以使用defaultdict 来实现,如下所示:

from collections import defaultdict

N = defaultdict(dict)

然后,当您开始获取输入时,只需为每个输入边执行N[start][end] = weight。如果您有一些没有出站边的节点(您需要将内部字典的键与外部字典结合以确保您拥有它们全部),那么这组节点将更加棘手。但是即使没有完整的节点列表,很多算法也能正常工作。

邻接矩阵稍微复杂一些,因为您需要知道节点的数量才能正确设置其维度。如果你提前知道,那就很简单了:

number_of_nodes = 8
_ = float("inf")

N = [[_]*number_of_nodes for i in number_of_nodes]

如果您不这样做,您可能需要扫描作为输入获得的边以找到编号最高的节点,然后使用上面相同的代码来制作矩阵。例如,如果您的边以(start, end, weight) 3 元组列表的形式提供,您可以使用:

number_of_nodes = max(max(start, end) for start, end, weight in edges)

【讨论】:

  • 感谢您的意见,看来我还需要学习更多关于如何在 python 中编写代码的方法,例如 number_of_nodes = max(max(start, end) for开始,结束,边缘重量),感谢您的输入,我将尝试使用您提供的一些东西!
  • 当说缺少某些行时,这会创建邻接矩阵吗(比如节点是 1 2 5 6 这会创建一个 6X6 或 4x4 矩阵吗?)
【解决方案3】:

希望下面的例子对你有帮助 它既有初始化图,也有用户自定义

class Graph:
"""
  Read the Intialized Graph and Create a Adjacency list out of it 
   There could be cases where in the initialized graph <map> link
  issues are not maintained
   for example node 2 to 1 link 
    2->1
   there needs to be a link then since undirected Graph
    1->2
"""

def __init__(self,Graph_init):
    self.edge={}
    for keys,values in Graph_init.items():
         for value in values:
             self.addEdge(keys,value);

"""
Add a vertex to graph map
structure is
int => int list
"""
def addVertex(self,v):
    if v not in self.edge:
        self.edge[v]=[]
"""
Add Edge from both vertex to each other
Make sure the nodes are present   

"""
def addEdge(self,u,v): 如果你不在 self.edge: self.addVertex(u) 如果 v 不在 self.edge 中: self.addVertex(v) 如果你不在 self.edge[v] 中: self.edge[v].append(u) 如果 v 不在 self.edge[u] 中: self.edge[u].append(v)

def isEdge(self,u,v):
    if u not in self.edge:
        return False
    if v not in self.edge:
        return False 
    return  u in self.edge[v] 

def display(self):
    for keys,values in self.edge.items():
        print(keys,":=>",values)

"""A initalized Graph (not in form of adjaceny list"""
Graph_init = {1:[2,3,5],
          2:[1,4],
          3:[1,6]};

"""Default constrcutor takes care of making the initialzed map to adjaceny 
list"""                 
g=Graph(Graph_init)
g.addVertex(1)
g.addVertex(2) 
g.addVertex(3)
g.addEdge(1,2)
g.addEdge(3,2)
g.display();

【讨论】:

    猜你喜欢
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2014-10-19
    相关资源
    最近更新 更多