蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线对比邻接矩阵与邻接表相邻节点迭代器并验证 Graph 抽象接口多态

PYTHONWindows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。explore-graph-theory-iter.py
explore-graph-theory-iter.py202 行
"""Offline algorithm verification lab for Chapter 41 (graph-theory-iter)."""
from abc import ABC, abstractmethod
import json

VERSION = "CPython 3.12.14 offline DSA verifier (graph-theory-iter)"


class Graph(ABC):
    @abstractmethod
    def V(self) -> int: ...

    @abstractmethod
    def E(self) -> int: ...

    @abstractmethod
    def add_edge(self, v: int, w: int) -> None: ...

    @abstractmethod
    def has_edge(self, v: int, w: int) -> bool: ...

    @abstractmethod
    def adj(self, v: int): ...

    @abstractmethod
    def show(self) -> list: ...


class DenseGraphIterator(Graph):
    def __init__(self, n: int, directed: bool = False):
        self.n = n
        self.m = 0
        self.directed = directed
        self.g = [[False] * n for _ in range(n)]
        self.adj_scan_ops = 0

    def V(self) -> int:
        return self.n

    def E(self) -> int:
        return self.m

    def has_edge(self, v: int, w: int) -> bool:
        assert 0 <= v < self.n and 0 <= w < self.n
        return self.g[v][w]

    def add_edge(self, v: int, w: int) -> None:
        assert 0 <= v < self.n and 0 <= w < self.n
        if self.has_edge(v, w):
            return
        self.g[v][w] = True
        if not self.directed:
            self.g[w][v] = True
        self.m += 1

    def adj(self, v: int) -> list:
        assert 0 <= v < self.n
        adj_v = []
        for i in range(self.n):
            self.adj_scan_ops += 1
            if self.g[v][i]:
                adj_v.append(i)
        return adj_v

    def show(self) -> list:
        return [f"vertex {v}: {list(self.adj(v))}" for v in range(self.n)]


class SparseGraphIterator(Graph):
    def __init__(self, n: int, directed: bool = False):
        self.n = n
        self.m = 0
        self.directed = directed
        self.g = [[] for _ in range(n)]
        self.adj_yield_ops = 0

    def V(self) -> int:
        return self.n

    def E(self) -> int:
        return self.m

    def has_edge(self, v: int, w: int) -> bool:
        assert 0 <= v < self.n and 0 <= w < self.n
        return w in self.g[v]

    def add_edge(self, v: int, w: int) -> None:
        assert 0 <= v < self.n and 0 <= w < self.n
        self.g[v].append(w)
        if v != w and not self.directed:
            self.g[w].append(v)
        self.m += 1

    def adj(self, v: int):
        assert 0 <= v < self.n
        for w in self.g[v]:
            self.adj_yield_ops += 1
            yield w

    def show(self) -> list:
        return [f"vertex {v}: {list(self.adj(v))}" for v in range(self.n)]


def collect_degree_profile(graph: Graph) -> dict:
    """Algorithm written purely against the abstract Graph interface."""
    return {v: sorted(list(graph.adj(v))) for v in range(graph.V())}


def case_dense_graph_adj_iterator():
    dg = DenseGraphIterator(6, directed=False)
    for u, v in [(0, 1), (0, 5), (0, 2), (1, 2), (3, 4)]:
        dg.add_edge(u, v)
    neighbors_0 = dg.adj(0)
    neighbors_3 = dg.adj(3)
    expected = {
        "neighbors_0": [1, 2, 5],
        "neighbors_3": [4],
        "scan_ops_for_two_calls": 12,
    }
    actual = {
        "neighbors_0": neighbors_0,
        "neighbors_3": neighbors_3,
        "scan_ops_for_two_calls": dg.adj_scan_ops,
    }
    return {
        "name": "dense_graph_adj_iterator",
        "summary": "验证邻接矩阵 adj(v) 扫描整行 O(V) 返回升序相邻节点列表,2 次调用扫描 2*V=12 格",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_sparse_graph_adj_iterator():
    sg = SparseGraphIterator(6, directed=False)
    for u, v in [(0, 1), (0, 5), (0, 2), (1, 2), (3, 4)]:
        sg.add_edge(u, v)
    neighbors_0 = list(sg.adj(0))
    neighbors_3 = list(sg.adj(3))
    expected = {
        "neighbors_0": [1, 5, 2],
        "neighbors_3": [4],
        "yield_ops_equals_degrees": 4,
    }
    actual = {
        "neighbors_0": neighbors_0,
        "neighbors_3": neighbors_3,
        "yield_ops_equals_degrees": sg.adj_yield_ops,
    }
    return {
        "name": "sparse_graph_adj_iterator",
        "summary": "验证邻接表 adj(v) 直接按插入顺序迭代实际邻边,总迭代步数等于顶点度数之和 O(deg(v))",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_unified_graph_interface_polymorphism():
    edges = [(0, 1), (0, 2), (1, 3), (2, 3), (3, 4), (4, 5)]
    dense = DenseGraphIterator(6, directed=False)
    sparse = SparseGraphIterator(6, directed=False)
    for u, v in edges:
        dense.add_edge(u, v)
        sparse.add_edge(u, v)

    prof_dense = collect_degree_profile(dense)
    prof_sparse = collect_degree_profile(sparse)
    expected = {
        "profiles_identical": True,
        "dense_V_E": [6, 6],
        "sparse_V_E": [6, 6],
        "show_lines_count": 6,
        "vertex_3_adj": [1, 2, 4],
    }
    actual = {
        "profiles_identical": prof_dense == prof_sparse,
        "dense_V_E": [dense.V(), dense.E()],
        "sparse_V_E": [sparse.V(), sparse.E()],
        "show_lines_count": len(dense.show()),
        "vertex_3_adj": prof_sparse[3],
    }
    return {
        "name": "unified_graph_interface_polymorphism",
        "summary": "验证统一抽象 Graph 接口解耦底层存储,同一图算法在邻接矩阵与邻接表上产出完全一致的邻接视图",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_dense_graph_adj_iterator(),
        case_sparse_graph_adj_iterator(),
        case_unified_graph_interface_polymorphism(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。

入口文件:projects/data-structures-graph-theory-iter-lab/explore-graph-theory-iter.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-graph-theory-iter.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:数据结构与算法

课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip

下载课程关联工程包:数据结构与算法

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2663.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习