When implementing algorithms, enforce correctness and reliability by following this checklist:
1) Validate stated preconditions (and document them)
2) Handle numerical/semantic edge cases explicitly
math.isclose() (and/or symmetric checks) instead of direct comparisons.== 0.0.3) Ensure algorithm invariants are implemented (especially graph/search)
reverse()) and add a brief comment explaining why.4) Avoid unnecessary extra passes
Example pattern (single-pass grouping + clear precondition validation):
from collections import defaultdict
def group_by_priority(items: list[dict]) -> dict[str, list[dict]]:
grouped: dict[str, list[dict]] = defaultdict(list)
for item in items:
grouped[item["priority"]].append(item)
return dict(grouped)
def cyclic_sort_guard(nums: list[int]) -> None:
n = len(nums)
if any(x < 1 or x > n for x in nums):
raise ValueError("Cyclic sort requires all values in the range [1, len(nums)]")
if len(set(nums)) != n:
raise ValueError("Cyclic sort requires no duplicates")
Adopting this standard will reduce subtle correctness bugs (wrong logic/invariants), runtime failures (invalid inputs/infinite loops), and precision-related issues, while also improving efficiency for larger inputs.
Enter the URL of a public GitHub repository