"""Implement and test the result of two small coding-agent tasks."""
import argparse
from bisect import bisect_left
from functools import reduce
from pathlib import Path
import json
def gcd(left: int, right: int) -> int:
"""Return the nonnegative greatest common divisor of two integers."""
left, right = abs(left), abs(right)
while right:
left, right = right, left % right
return left
class GcdCalculator:
def calculate(self, values: list[int]) -> int:
"""Compute the divisor shared by all supplied integers."""
if not values:
raise ValueError("supply at least one integer")
return reduce(gcd, values, 0)
def binary_search(values: list[int], target: int) -> int:
"""Find the first position of the target in an ascending list or return -1."""
pos = bisect_left(values, target)
return pos if pos < len(values) and values[pos] == target else -1
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="operation", required=True)
hello = commands.add_parser("hello")
hello.add_argument("directory", type=Path)
arithmetic = commands.add_parser("gcd")
arithmetic.add_argument("values", nargs="+", type=int)
search = commands.add_parser("search")
search.add_argument("target", type=int)
search.add_argument("values", nargs="*", type=int)
args = parser.parse_args()
if args.operation == "hello":
target = args.directory / "hello.txt"
try:
with target.open("x", encoding="utf-8", newline="\n") as handle:
handle.write("你好,蓝色天空网!\n")
except FileExistsError:
parser.exit(2, "hello.txt already exists\n")
result = target.name
elif args.operation == "gcd":
result = GcdCalculator().calculate(args.values)
else:
if any(a > b for a, b in zip(args.values, args.values[1:])):
parser.exit(2, "expected ascending input\n")
result = binary_search(args.values, args.target)
print(json.dumps(result))
if __name__ == "__main__":
main()
本例需在 Python 3.10 或以上版本,离线运行。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Python 3.10 或以上版本,离线运行。
入口文件:projects/vibe-coding-kilo/practice.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
practice.py,或下载右侧课程工程包。 - 确认本地已准备 Python 3.10 或以上版本,离线运行。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a385.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a390.zip