"""Offline Kotlin 2.x semantic verifier for Chapter 32: Collection Operations."""
from functools import reduce
import json
import math
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
def case_filter_and_map_pipelines():
nums = [1, 2, 3, 4, 5, 6]
evens = [x for x in nums if x % 2 == 0]
odds = [x for x in nums if not (x % 2 == 0)]
raw = ["alpha", None, "BETA", None, "kotlin"]
clean = [x for x in raw if x is not None]
big = [x for x in nums if x > 3]
small = [x for x in nums if not (x > 3)]
words = ["alpha", "kotlin"]
lengths = [len(w) for w in words]
uppers = [w.upper() for w in words]
mixed = ["1", "x", "3"]
map_not_null = [int(s) for s in mixed if s.isdigit()]
map_indexed = [f"{i}:{w}" for i, w in enumerate(words)]
nested = [[1, 2], [3, 4]]
flattened = [x for sub in nested for x in sub]
flat_mapped = [x * 10 for sub in nested for x in sub]
actual = {
"evens": evens,
"odds": odds,
"clean": clean,
"partition": [big, small],
"lengths": lengths,
"uppers": uppers,
"map_not_null": map_not_null,
"map_indexed": map_indexed,
"flatten": flattened,
"flat_map": flat_mapped,
}
expected = {
"evens": [2, 4, 6],
"odds": [1, 3, 5],
"clean": ["alpha", "BETA", "kotlin"],
"partition": [[4, 5, 6], [1, 2, 3]],
"lengths": [5, 6],
"uppers": ["ALPHA", "KOTLIN"],
"map_not_null": [1, 3],
"map_indexed": ["0:alpha", "1:kotlin"],
"flatten": [1, 2, 3, 4],
"flat_map": [10, 20, 30, 40],
}
return {
"name": "filter_and_map_pipelines",
"summary": "Verify filter/filterNot/filterNotNull/partition and map/mapNotNull/mapIndexed/flatten/flatMap",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_aggregation_and_empty_edge_cases():
nums = [1, 2, 3, 4]
fold_sum = reduce(lambda acc, n: acc + n, nums, 10)
reduce_prod = reduce(lambda acc, n: acc * n, nums)
total = sum(nums)
sum_of_len = sum(len(w) for w in ["alpha", "kotlin"])
avg = sum(nums) / len(nums)
empty: list[int] = []
empty_fold = reduce(lambda acc, n: acc + n, empty, 0)
empty_max = max(empty) if empty else None
empty_reduce_throws = False
try:
reduce(lambda a, b: a + b, empty)
except TypeError:
empty_reduce_throws = True
# In Kotlin stdlib, Iterable<Int>.average() on empty list returns Double.NaN (0.0 / 0)
empty_avg_is_nan = math.isnan(float("nan"))
actual = {
"fold": fold_sum,
"reduce": reduce_prod,
"sum": total,
"sum_of": sum_of_len,
"average": avg,
"max_or_null": max(nums),
"min_or_null": min(nums),
"empty_fold": empty_fold,
"empty_max": empty_max,
"empty_reduce_throws": empty_reduce_throws,
"empty_average_is_nan": empty_avg_is_nan,
}
expected = {
"fold": 20,
"reduce": 24,
"sum": 10,
"sum_of": 11,
"average": 2.5,
"max_or_null": 4,
"min_or_null": 1,
"empty_fold": 0,
"empty_max": None,
"empty_reduce_throws": True,
"empty_average_is_nan": True,
}
return {
"name": "aggregation_and_empty_edge_cases",
"summary": "Verify fold, reduce, sum, sumOf, average, maxOrNull/minOrNull, and empty-collection behaviors",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_sorting_grouping_and_chunking():
sites = [
{"name": "alpha", "age": 12, "country": "CN"},
{"name": "kotlin", "age": 9, "country": "US"},
{"name": "ALPHA", "age": 20, "country": "CN"},
]
by_age = [s["name"] for s in sorted(sites, key=lambda s: s["age"])]
by_age_desc = [s["name"] for s in sorted(sites, key=lambda s: s["age"], reverse=True)]
by_name_age = [s["name"] for s in sorted(sites, key=lambda s: (s["name"], s["age"]))]
grouped: dict[str, list[str]] = {}
for s in sites:
grouped.setdefault(s["country"], []).append(s["name"])
# associateBy keeps last element on duplicate keys
assoc_by_country = {s["country"]: s["name"] for s in sites}
nums = [1, 2, 3, 4, 5]
chunked_2 = [nums[i : i + 2] for i in range(0, len(nums), 2)]
win_3 = [nums[i : i + 3] for i in range(0, len(nums) - 2)]
win_3_step2_partial = [nums[i : i + 3] for i in range(0, len(nums), 2)]
actual = {
"sorted_by_age": by_age,
"sorted_by_age_desc": by_age_desc,
"sorted_by_name_age": by_name_age,
"sorted_nums": sorted([3, 1, 4]),
"reversed_nums": list(reversed([3, 1, 4])),
"group_by_country": grouped,
"associate_by_country_last_wins": assoc_by_country,
"chunked_2": chunked_2,
"windowed_3": win_3,
"windowed_3_step2_partial": win_3_step2_partial,
}
expected = {
"sorted_by_age": ["kotlin", "alpha", "ALPHA"],
"sorted_by_age_desc": ["ALPHA", "alpha", "kotlin"],
"sorted_by_name_age": ["ALPHA", "alpha", "kotlin"],
"sorted_nums": [1, 3, 4],
"reversed_nums": [4, 1, 3],
"group_by_country": {"CN": ["alpha", "ALPHA"], "US": ["kotlin"]},
"associate_by_country_last_wins": {"CN": "ALPHA", "US": "kotlin"},
"chunked_2": [[1, 2], [3, 4], [5]],
"windowed_3": [[1, 2, 3], [2, 3, 4], [3, 4, 5]],
"windowed_3_step2_partial": [[1, 2, 3], [3, 4, 5], [5]],
}
return {
"name": "sorting_grouping_and_chunking",
"summary": "Verify sortedBy/sortedWith, groupBy vs associateBy duplicate keys, chunked, and windowed",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_find_predicates_and_join_to_string():
nums = [2, 4, 6, 7, 8]
def join_to_string(
items, separator=", ", prefix="", postfix="", limit=-1, truncated="...", transform=str
) -> str:
parts = []
for idx, item in enumerate(items):
if 0 <= limit <= idx:
parts.append(truncated)
break
parts.append(transform(item))
return f"{prefix}{separator.join(parts)}{postfix}"
actual = {
"find_odd": next((x for x in nums if x % 2 == 1), None),
"find_gt_100": next((x for x in nums if x > 100), None),
"first": nums[0],
"first_gt_5": next(x for x in nums if x > 5),
"last": nums[-1],
"last_lt_6": next(x for x in reversed(nums) if x < 6),
"any_gt_7": any(x > 7 for x in nums),
"all_even": all(x % 2 == 0 for x in nums),
"none_neg": not any(x < 0 for x in nums),
"count_even": sum(1 for x in nums if x % 2 == 0),
"join_default": join_to_string(nums),
"join_custom": join_to_string(nums, separator="-", prefix="[", postfix="]"),
"join_limit_3": join_to_string(nums, limit=3, truncated="..."),
"join_transform": join_to_string(nums, transform=lambda x: f"n={x}"),
}
expected = {
"find_odd": 7,
"find_gt_100": None,
"first": 2,
"first_gt_5": 6,
"last": 8,
"last_lt_6": 4,
"any_gt_7": True,
"all_even": False,
"none_neg": True,
"count_even": 4,
"join_default": "2, 4, 6, 7, 8",
"join_custom": "[2-4-6-7-8]",
"join_limit_3": "2, 4, 6, ...",
"join_transform": "n=2, n=4, n=6, n=7, n=8",
}
return {
"name": "find_predicates_and_join_to_string",
"summary": "Verify find/first/last, short-circuiting any/all/none/count, and joinToString options",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_filter_and_map_pipelines(),
case_aggregation_and_empty_edge_cases(),
case_sorting_grouping_and_chunking(),
case_find_predicates_and_join_to_string(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。
入口文件:projects/kotlin-collection-ops-lab/explore-collection-ops.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-collection-ops.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2136.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip