You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于给定的Vertex类创建邻接表?

问题描述

我写了下面的Vertex类:

class Vertex:  # vertex = node
    def __init__(self, node):
        self.id = node
        self.adjacent = {}

    def __str__(self):
        return str(self.id) + ' adjacent: ' + str([x.id for x in self.adjacent])

但我不清楚该如何创建邻接表!

我尝试了多种方法,但通常会遇到类似如下的错误:

bound<method vertex

(抱歉,我现在无法复现这个错误,所以不确定具体内容)

我现在陷入了困境,非常感谢任何形式的帮助。谢谢。


邻接表创建方案

你的Vertex类已经具备存储邻接节点的基础(adjacent字典),下面是完整的实现思路和示例:

1. 用图类统一管理顶点

先写一个Graph类,负责管理所有顶点,提供添加顶点、边的方法:

class Graph:
    def __init__(self):
        self.vertices = {}  # 用字典存所有顶点,key是顶点id,value是Vertex实例

    def add_vertex(self, vertex_id):
        # 顶点不存在则创建
        if vertex_id not in self.vertices:
            self.vertices[vertex_id] = Vertex(vertex_id)
        return self.vertices[vertex_id]

    def add_edge(self, from_id, to_id, weight=0):
        # 确保两个顶点都已创建
        from_vertex = self.add_vertex(from_id)
        to_vertex = self.add_vertex(to_id)
        # 给起点的邻接表添加终点,可附带权重
        from_vertex.adjacent[to_vertex] = weight
        # 如果是无向图,需要反向也加一条边
        # to_vertex.adjacent[from_vertex] = weight

2. 实际使用示例

# 创建图实例
g = Graph()

# 添加顶点
g.add_vertex('A')
g.add_vertex('B')
g.add_vertex('C')

# 添加边
g.add_edge('A', 'B', 5)
g.add_edge('A', 'C', 3)
g.add_edge('B', 'C', 1)

# 打印顶点A的邻接情况
print(g.vertices['A'])
# 输出:A adjacent: ['B', 'C']

3. 你遇到的错误原因推测

你提到的bound<method vertex错误,大概率是把Vertex类本身当成实例使用了,比如误写了Vertex.adjacent(访问类属性)而不是某个Vertex实例的adjacent,或者添加邻接节点时传入了Vertex类而非实例。

错误示例:

v = Vertex('A')
v.adjacent[Vertex] = 5  # 这里传入了Vertex类,不是具体实例

正确写法:

v1 = Vertex('A')
v2 = Vertex('B')
v1.adjacent[v2] = 5  # 传入Vertex实例

内容的提问来源于stack exchange,提问作者iaivazovski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 05:23:25