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

运行离线 Python 校验:Swift Set 集合代数、包含关系与八大高阶函数链式管道

PYTHONWindows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。explore-set-higher-order.py
explore-set-higher-order.py217 行
"""Offline CPython 3.12.14 semantic verifier for Swift Set & Higher-Order Functions (CH35)."""
import json
from functools import reduce


def swift_set_remove(s: set, elem):
    if elem in s:
        s.remove(elem)
        return elem
    return None


def case_set_creation_mutation_and_algebra():
    langs = {"Swift", "Kotlin", "Rust"}
    langs.add("Go")
    dedup = sorted({1, 2, 2, 3, 3, 3})

    s = {1, 2, 3}
    s.add(4)
    s.discard(1)
    s |= {5, 6}           # formUnion
    s &= {2, 3, 5}        # formIntersection
    s -= {3}              # subtract

    tags = {"SWIFT", "swift"}
    rem_ok = swift_set_remove(tags, "swift")
    rem_miss = swift_set_remove(tags, "missing")

    a = {1, 2, 3, 4}
    b = {3, 4, 5, 6}
    actual = {
        "langs_count": len(langs),
        "contains_swift": "Swift" in langs,
        "contains_python": "Python" in langs,
        "langs_sorted": sorted(langs),
        "dedup": dedup,
        "in_place_ops": sorted(s),
        "remove_results": [rem_ok, rem_miss or "不存在"],
        "union": sorted(a | b),
        "intersection": sorted(a & b),
        "subtracting": sorted(a - b),
        "symmetric_difference": sorted(a ^ b),
    }
    expected = {
        "langs_count": 4,
        "contains_swift": True,
        "contains_python": False,
        "langs_sorted": ["Go", "Kotlin", "Rust", "Swift"],
        "dedup": [1, 2, 3],
        "in_place_ops": [2, 5],
        "remove_results": ["swift", "不存在"],
        "union": [1, 2, 3, 4, 5, 6],
        "intersection": [3, 4],
        "subtracting": [1, 2],
        "symmetric_difference": [1, 2, 5, 6],
    }
    return {
        "name": "set_creation_mutation_and_algebra",
        "summary": "Verify Set deduplication, in-place form* operations, optional remove return, and pure union/intersection/subtracting/symmetricDifference.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_set_relations():
    small = {"Swift"}
    big = {"Swift", "Kotlin", "Rust"}
    same = {"Swift", "Kotlin", "Rust"}
    empty: set[str] = set()

    actual = {
        "is_subset": small <= big,
        "is_superset": big >= small,
        "is_strict_subset": small < big,
        "is_disjoint": big.isdisjoint({"Go"}),
        "equal_is_subset": big <= same,
        "equal_is_strict_subset": big < same,
        "empty_is_subset_of_all": empty <= big and empty <= empty,
    }
    expected = {
        "is_subset": True,
        "is_superset": True,
        "is_strict_subset": True,
        "is_disjoint": True,
        "equal_is_subset": True,
        "equal_is_strict_subset": False,
        "empty_is_subset_of_all": True,
    }
    return {
        "name": "set_relations_subset_disjoint",
        "summary": "Verify isSubset, isSuperset, isStrictSubset (false on equal sets), isDisjoint, and empty-set subset property.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_higher_order_core():
    numbers = [1, 2, 3, 4, 5]
    doubled = [x * 2 for x in numbers]
    upper_names = [s.upper() for s in ["alpha", "swift"]]
    evens = [x for x in numbers if x % 2 == 0]
    set_map_lengths = sorted([len(x) for x in {"Swift", "Go", "Rust"}])

    sum_val = reduce(lambda acc, x: acc + x, numbers, 0)
    max_val = reduce(lambda acc, x: acc if acc > x else x, numbers, numbers[0])

    raw = ["1", "2", "invalid", "4"]
    compact_ints = []
    for tok in raw:
        try:
            compact_ints.append(int(tok))
        except ValueError:
            pass

    nested = [[1, 2], [3, 4], [5]]
    flat_nums = [x for sub in nested for x in sub]
    sentences = ["Hello Swift", "Welcome to BlueSky"]
    flat_words = [w for s in sentences for w in s.split(" ")]

    actual = {
        "map_doubled": doubled,
        "map_upper": upper_names,
        "filter_evens": evens,
        "set_map_lengths": set_map_lengths,
        "reduce_sum": sum_val,
        "reduce_max": max_val,
        "compact_map": compact_ints,
        "flat_map_nums": flat_nums,
        "flat_map_words": flat_words,
    }
    expected = {
        "map_doubled": [2, 4, 6, 8, 10],
        "map_upper": ["ALPHA", "SWIFT"],
        "filter_evens": [2, 4],
        "set_map_lengths": [2, 4, 5],
        "reduce_sum": 15,
        "reduce_max": 5,
        "compact_map": [1, 2, 4],
        "flat_map_nums": [1, 2, 3, 4, 5],
        "flat_map_words": ["Hello", "Swift", "Welcome", "to", "BlueSky"],
    }
    return {
        "name": "higher_order_map_filter_reduce_compact_flat",
        "summary": "Verify map, filter, reduce, compactMap (dropping nil), and flatMap (flattening nested sequences).",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_foreach_sorted_contains_chaining():
    numbers = [1, 2, 3, 4, 5]
    side_effects: list[str] = []
    for n in numbers:
        side_effects.append(f"元素: {n}")

    desc_nums = sorted(numbers, reverse=True)
    orgs = [("BlueSky", 2014), ("Google", 1998), ("Apple", 1976)]
    by_year = [o[0] for o in sorted(orgs, key=lambda t: t[1])]

    has_gt_4 = any(x > 4 for x in numbers)
    has_gt_100 = any(x > 100 for x in numbers)

    # Chained pipeline: (1...10).filter(even).map(square).reduce(0, +)
    chain_sum = reduce(
        lambda a, b: a + b,
        [x * x for x in range(1, 11) if x % 2 == 0],
        0,
    )
    words = ["Swift", "Kotlin", "Swift", "Rust"]
    chain_summary = ", ".join(sorted([w.upper() for w in set(words)]))

    actual = {
        "foreach_count": len(side_effects),
        "sorted_desc": desc_nums,
        "sorted_orgs": by_year,
        "contains_gt_4": has_gt_4,
        "contains_gt_100": has_gt_100,
        "chain_even_square_sum": chain_sum,
        "chain_dedup_upper_joined": chain_summary,
    }
    expected = {
        "foreach_count": 5,
        "sorted_desc": [5, 4, 3, 2, 1],
        "sorted_orgs": ["Apple", "Google", "BlueSky"],
        "contains_gt_4": True,
        "contains_gt_100": False,
        "chain_even_square_sum": 220,
        "chain_dedup_upper_joined": "KOTLIN, RUST, SWIFT",
    }
    return {
        "name": "foreach_sorted_contains_and_chaining",
        "summary": "Verify forEach side-effects, sorted(by:), contains(where:), and multi-stage functional pipelines.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main() -> None:
    report = {
        "version": "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)",
        "cases": [
            case_set_creation_mutation_and_algebra(),
            case_set_relations(),
            case_higher_order_core(),
            case_foreach_sorted_contains_chaining(),
        ],
    }
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。

入口文件:projects/swift-set-higher-order-lab/explore-set-higher-order.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-set-higher-order.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Swift

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

下载课程关联工程包:Swift

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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