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

Python如何编写返回无向路径图的pathGraph自定义函数?

Python无向路径图生成函数修正方案

问题根因

原有代码仅为每个节点添加了序号更大的后继相邻节点,未补全序号更小的前驱相邻节点,因此生成的是单向边的有向图结构,不符合无向图要求。

修正后代码

def pathGraph(n):
    d = dict()
    for x in range(n):
        neighbors = []
        # 存在前驱节点则加入
        if x > 0:
            neighbors.append(x - 1)
        # 存在后继节点则加入
        if x < n - 1:
            neighbors.append(x + 1)
        d[x] = neighbors
    return d

效果验证

调用pathGraph(4)即可输出预期结果:{0: [1], 1: [0, 2], 2: [1, 3], 3: [2]}。

简化写法(可选)

如果偏好更简洁的代码,可以用字典推导式+列表推导式实现相同逻辑:

def pathGraph(n):
    return {x: [i for i in (x-1, x+1) if 0 <= i < n] for x in range(n)}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:09:03