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

运行本章核心实例

PYTHON本地 Python 环境python-operator.py
python-operator.py180 行
"""蓝色天空网 mbsky.com · operator 对应运算与错误边界实验。"""
from argparse import ArgumentParser
import builtins
from functools import cmp_to_key
import operator as op
from pathlib import Path
import platform
import sys

sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks


class ComparisonToken:
    def __lt__(self, other):
        return ("checked", other)


class SizeByLength:
    def __len__(self):
        return 0


class DeclinesOrder:
    def __lt__(self, other):
        return NotImplemented


class RightOrder:
    def __gt__(self, other):
        return "right comparator ran"


class Matrix:
    def __init__(self, rows):
        self.rows = tuple(tuple(row) for row in rows)
        if not self.rows or not self.rows[0] or any(len(row) != len(self.rows[0]) for row in self.rows):
            raise ValueError("matrix rows must be rectangular and nonempty")

    def __matmul__(self, other):
        if not isinstance(other, Matrix):
            return NotImplemented
        if len(self.rows[0]) != len(other.rows):
            raise ValueError("matrix inner dimensions must match")
        columns = tuple(zip(*other.rows, strict=True))
        return Matrix(tuple(tuple(sum(a * b for a, b in zip(row, column, strict=True))
                                  for column in columns) for row in self.rows))


def compare(check):
    cases = [
        ("lt", (True, False, False)),
        ("le", (True, False, True)),
        ("eq", (False, False, True)),
        ("ne", (True, True, False)),
        ("ge", (False, True, True)),
        ("gt", (False, True, False)),
    ]
    for name, expected in cases:
        operation = getattr(op, name)
        result = tuple(operation(a, b) for a, b in [(7, 12), (12, 7), (7, 7)])
        check.eq(name, result, expected)
        result = tuple(operation(a, b) for a, b in [("A10", "B03"), ("B03", "A10"), ("A10", "A10")])
        check.eq(name + " string", result, expected)
        alias = getattr(op, "__" + name + "__")
        check.eq(name + " dunder alias", tuple(alias(a, b) for a, b in [(7, 12), (12, 7), (7, 7)]), expected)
    a, b = [7, 12], [7, 12]
    same = a
    check.eq("list equality compares contents", (op.eq(a, b), op.eq(a, [7, 13])), (True, False))
    check.eq("is", (op.is_(a, same), op.is_(a, b)), (True, False))
    check.eq("is-not", (op.is_not(a, b), op.is_not(a, same)), (True, False))
    check.eq("rich comparison can return a nonboolean", op.lt(ComparisonToken(), 7), ("checked", 7))
    check.eq("reflected comparison after NotImplemented", op.lt(DeclinesOrder(), RightOrder()), "right comparator ran")
    check.raises("unsupported ordering raises TypeError", TypeError, lambda: op.lt(7, "seven"))
    check.eq("truth", (op.truth([]), op.truth([0]), op.truth(SizeByLength())), (False, True, False))
    check.eq("not", (op.not_([]), op.not_([0])), (True, False))
    check.eq("cmp is absent in Python 3", hasattr(builtins, "cmp"), False)

    def compare_lengths(left, right):
        return (len(left) > len(right)) - (len(left) < len(right))

    values = ["wide", "a", "bc", "d"]
    check.eq("three-way comparison returns sign", tuple(compare_lengths(*p) for p in
             [("a", "wide"), ("bc", "xx"), ("wide", "a")]), (-1, 0, 1))
    check.eq("cmp_to_key migrates a comparison callback", sorted(values, key=cmp_to_key(compare_lengths)),
             ["a", "d", "bc", "wide"])


def calculate(check):
    check.eq("add", op.add(14, 6), 20)
    check.eq("sub", op.sub(14, 6), 8)
    check.eq("mul", op.mul(14, 6), 84)
    check.eq("truediv", op.truediv(7, 2), 3.5)
    check.eq("floordiv", (op.floordiv(7, 2), op.floordiv(-7, 2)), (3, -4))
    check.eq("mod-number", (op.mod(-7, 2), op.mod(7, -2)), (1, -1))
    check.eq("division identity", op.floordiv(-7, 2) * 2 + op.mod(-7, 2), -7)
    check.raises("true division by zero", ZeroDivisionError, lambda: op.truediv(1, 0))
    check.raises("floor division by zero", ZeroDivisionError, lambda: op.floordiv(1, 0))
    check.eq("pow", op.pow(3, 4), 81)
    check.eq("neg", (op.neg(4), op.neg(-4)), (-4, 4))
    check.eq("pos", (op.pos(4), op.pos(-4)), (4, -4))

    check.eq("and", (op.and_(0b1100, 0b1010), op.and_({1, 2}, {2, 3})), (0b1000, {2}))
    check.eq("xor", op.xor(0b1100, 0b1010), 0b0110)
    check.eq("invert", op.invert(5), -6)
    check.eq("or", op.or_(0b1100, 0b1010), 0b1110)
    check.eq("lshift", op.lshift(5, 2), 20)
    check.eq("rshift", (op.rshift(5, 1), op.rshift(-5, 1)), (2, -3))
    check.raises("negative shift count rejected", ValueError, lambda: op.lshift(2, -1))
    visited = []

    def right():
        visited.append("right")
        return 1

    check.eq("and expression short circuits", (0 and right(), visited), (0, []))
    check.eq("bitwise function evaluates both arguments", (op.and_(0, right()), visited), (0, ["right"]))

    left = Matrix([[2, 1, 0], [3, 0, 1]])
    right_matrix = Matrix([[1, 4], [2, 0], [3, 2]])
    wanted = ((4, 8), (6, 14))
    check.eq("matmul", (op.matmul(left, right_matrix).rows, (left @ right_matrix).rows), (wanted, wanted))
    check.raises("matrix inner dimensions checked", ValueError, lambda: op.matmul(left, left))
    check.raises("plain lists do not implement matrix multiplication", TypeError, lambda: op.matmul([[1]], [[2]]))


def containers(check):
    check.eq("concat", (op.concat("north", "-gate"), op.concat([1, 2], [3])), ("north-gate", [1, 2, 3]))
    check.raises("concat rejects integers", TypeError, lambda: op.concat(1, 2))
    check.eq("contains", (op.contains(["north", "west"], "north"), op.contains({"north": 7}, "north"),
                          op.contains({"north": 7}, 7)), (True, True, False))
    mapping = {"north": 7, "west": 3}
    check.eq("getitem-index", (op.getitem(mapping, "north"), op.getitem([7, 3], -1)), (7, 3))
    check.raises("missing mapping key", KeyError, lambda: op.getitem(mapping, "east"))
    check.raises("list index out of range", IndexError, lambda: op.getitem([7], 1))
    check.eq("setitem-index", (op.setitem(mapping, "north", 8), mapping), (None, {"north": 8, "west": 3}))
    check.eq("delitem-index", (op.delitem(mapping, "west"), mapping), (None, {"north": 8}))
    check.raises("tuple does not support assignment", TypeError, lambda: op.setitem((7,), 0, 8))

    values = [7, 12, 19, 24]
    selected = op.getitem(values, slice(1, 3))
    check.eq("getitem-slice", (selected, selected is values), ([12, 19], False))
    check.eq("setitem-slice", (op.setitem(values, slice(1, 3), [31, 37, 42]), values),
             (None, [7, 31, 37, 42, 24]))
    check.eq("delitem-slice", (op.delitem(values, slice(1, 3)), values), (None, [7, 42, 24]))
    check.raises("extended slice assignment requires equal size", ValueError,
                 lambda: op.setitem(values, slice(None, None, 2), [4]))
    check.eq("mod-text", op.mod("sensor %s counted %03d", ("A", 7)), "sensor A counted 007")


def numpy_checks(check):
    import numpy as np

    a = np.array([[2, 1], [0, 3]])
    b = np.array([[1, 4], [2, 0]])
    check.eq("NumPy matrix product", op.matmul(a, b).tolist(), [[4, 8], [6, 0]])
    check.eq("NumPy elementwise product is distinct", op.mul(a, b).tolist(), [[2, 4], [0, 0]])
    equality = op.eq(a, b)
    check.eq("NumPy rich comparison returns an array", (type(equality).__name__, equality.tolist()),
             ("ndarray", [[False, False], [False, False]]))
    check.raises("NumPy multi-element truth is ambiguous", ValueError, lambda: op.truth(equality))
    return np.__version__


def main():
    parser = ArgumentParser(description="Verify operator functions using owned inputs.")
    parser.add_argument("--numpy", action="store_true", help="Also run checks with an installed NumPy.")
    args = parser.parse_args()
    check = Checks()
    compare(check)
    calculate(check)
    containers(check)
    numpy = numpy_checks(check) if args.numpy else None
    check.finish("python-operator", python=platform.python_version(), platform=platform.platform(), numpy=numpy,
                 inputs="independent integer, string, list, mapping, class and matrix examples")


if __name__ == "__main__":
    main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 环境

入口文件:projects/python-lab/python-operator.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python-operator.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 环境。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

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

下载课程关联工程包:Python

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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