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

离线校验 SortedList 自动排序、TrimToSize、列表控件绑定与数字键双访问模式

PYTHONWindows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。explore-aspnet-sortedlist.py
explore-aspnet-sortedlist.py143 行
"""Offline ASP.NET WebForms verifier for Chapter 48 (sortedlist)."""
from __future__ import annotations

import bisect
import json

VERSION = "CPython 3.12.14 offline ASP.NET WebForms verifier (IIS/ASP.NET runtime absent)"


class DotNetSortedList:
    """Minimal model of System.Collections.SortedList (auto-sorted by key, indexable)."""

    def __init__(self, initial_capacity: int = 16) -> None:
        self._keys: list = []
        self._values: list = []
        self.capacity: int = initial_capacity

    def add(self, key, value) -> None:
        idx = bisect.bisect_left(self._keys, key)
        if idx < len(self._keys) and self._keys[idx] == key:
            raise KeyError(f"Duplicate key in SortedList: {key}")
        if len(self._keys) >= self.capacity:
            self.capacity = max(4, self.capacity * 2)
        self._keys.insert(idx, key)
        self._values.insert(idx, value)

    def trim_to_size(self) -> None:
        self.capacity = len(self._keys)

    def get_by_index(self, index: int):
        return self._values[index]

    def get_by_key(self, key):
        idx = bisect.bisect_left(self._keys, key)
        if idx < len(self._keys) and self._keys[idx] == key:
            return self._values[idx]
        raise KeyError(key)

    def entries(self) -> list[dict[str, object]]:
        return [{"Key": k, "Value": v} for k, v in zip(self._keys, self._values)]


def main() -> None:
    sl = DotNetSortedList(initial_capacity=16)
    sl.add("N", "Norway")
    sl.add("S", "Sweden")
    sl.add("F", "France")
    sl.add("I", "Italy")
    cap_before = sl.capacity
    sl.trim_to_size()
    cap_after = sl.capacity

    ordered_pairs = [(e["Key"], e["Value"]) for e in sl.entries()]
    radio_items = [{"value": e["Key"], "text": e["Value"]} for e in sl.entries()]
    dropdown_items = list(radio_items)

    # Case 3: Select index 0 ("F" -> "France") triggering displayMessage
    selected = radio_items[0]
    lbl1_text = f"Your favorite country is: {selected['text']}"

    # Case 4: Numeric keys auto-sort + dual key/index access + duplicate key rejection
    num_sl = DotNetSortedList()
    num_sl.add(30, "Thirty")
    num_sl.add(10, "Ten")
    num_sl.add(20, "Twenty")
    dup_error = False
    try:
        num_sl.add(20, "Duplicate")
    except KeyError:
        dup_error = True

    cases = [
        {
            "name": "sortedlist_auto_sort_and_trim",
            "summary": "验证 SortedList 插入 N/S/F/I 后自动按键字母升序排列,且 TrimToSize() 将容量从 16 收缩为 4",
            "expected": {
                "ordered": [("F", "France"), ("I", "Italy"), ("N", "Norway"), ("S", "Sweden")],
                "cap_before": 16,
                "cap_after": 4,
            },
            "actual": {
                "ordered": ordered_pairs,
                "cap_before": cap_before,
                "cap_after": cap_after,
            },
            "passed": (
                ordered_pairs == [("F", "France"), ("I", "Italy"), ("N", "Norway"), ("S", "Sweden")]
                and cap_before == 16
                and cap_after == 4
            ),
        },
        {
            "name": "sortedlist_bind_dropdown_and_radio",
            "summary": "验证绑定至 RadioButtonList 与 DropDownList 后选项严格按 F -> I -> N -> S 顺序渲染",
            "expected": {
                "radio_keys": ["F", "I", "N", "S"],
                "dropdown_texts": ["France", "Italy", "Norway", "Sweden"],
            },
            "actual": {
                "radio_keys": [x["value"] for x in radio_items],
                "dropdown_texts": [x["text"] for x in dropdown_items],
            },
            "passed": (
                [x["value"] for x in radio_items] == ["F", "I", "N", "S"]
                and [x["text"] for x in dropdown_items] == ["France", "Italy", "Norway", "Sweden"]
            ),
        },
        {
            "name": "sortedlist_selected_index_changed",
            "summary": "模拟选中排序后首项 F(France)并触发 displayMessage 输出标签文本",
            "expected": "Your favorite country is: France",
            "actual": lbl1_text,
            "passed": lbl1_text == "Your favorite country is: France",
        },
        {
            "name": "sortedlist_numeric_key_and_index",
            "summary": "验证 SortedList 兼具数字键自动排序、按键查询、按索引读取及重复键冲突检测",
            "expected": {
                "sorted_numeric_keys": [10, 20, 30],
                "by_index_1": "Twenty",
                "by_key_30": "Thirty",
                "duplicate_rejected": True,
            },
            "actual": {
                "sorted_numeric_keys": [e["Key"] for e in num_sl.entries()],
                "by_index_1": num_sl.get_by_index(1),
                "by_key_30": num_sl.get_by_key(30),
                "duplicate_rejected": dup_error,
            },
            "passed": (
                [e["Key"] for e in num_sl.entries()] == [10, 20, 30]
                and num_sl.get_by_index(1) == "Twenty"
                and num_sl.get_by_key(30) == "Thirty"
                and dup_error is True
            ),
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。

入口文件:projects/web-forms-aspnet-sortedlist-lab/explore-aspnet-sortedlist.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-aspnet-sortedlist.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Web Forms

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

下载课程关联工程包:Web Forms

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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