"""蓝色天空网 mbsky.com · 标准库文档和二分查找练习。"""
from bisect import bisect_left, bisect_right, insort_left
from inspect import signature
from pathlib import Path
import platform
import subprocess
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
def find(values, key):
position = bisect_left(values, key)
if position < len(values) and values[position] == key:
return position
return None
def main():
check = Checks()
version = subprocess.run([sys.executable, "--version"], capture_output=True,
text=True, check=True, timeout=15)
check.eq("interpreter version", version.stdout.strip(), "Python " + platform.python_version())
help_result = subprocess.run([sys.executable, "-I", "-B", "-m", "pydoc", "bisect"],
capture_output=True, text=True, encoding="utf-8",
check=True, timeout=15)
check.eq("local standard-library help", ("NAME" in help_result.stdout,
"bisect_left" in help_result.stdout, "bisect_right" in help_result.stdout), (True, True, True))
check.eq("installed key parameter", signature(bisect_left).parameters["key"].kind.name, "KEYWORD_ONLY")
values = [2, 4, 4, 7, 10]
left = bisect_left(values, 4)
right = bisect_right(values, 4)
check.eq("duplicate insertion boundaries", (left, right, values[left:right]), (1, 3, [4, 4]))
check.eq("insertion points at edges", (bisect_left(values, 1), bisect_left(values, 12)), (0, 5))
check.eq("binary membership checks actual value", (find(values, 4), find(values, 6), find(values, 12), find([], 4)),
(1, None, None, None))
check.eq("bisect does not mutate input", values, [2, 4, 4, 7, 10])
inserted = values.copy()
result = insort_left(inserted, 6)
check.eq("ordered insertion is a separate operation", (inserted, result), ([2, 4, 4, 6, 7, 10], None))
check.finish("python3-resources",python=platform.python_version(),platform=platform.platform(),
scope="Installed interpreter and independent standard-library exercise; no source scripts executed.")
if __name__ == "__main__":
main()
本例需在 Installed interpreter and independent standard-library exercise; no source scripts executed. 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Installed interpreter and independent standard-library exercise; no source scripts executed.
入口文件:projects/python-lab/python3-resources.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python3-resources.py,或下载右侧课程工程包。 - 确认本地已准备 Installed interpreter and independent standard-library exercise; no source scripts executed.。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip