Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions .claude/agents/contributing-reviewer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
---
name: contributing-reviewer
description: Reviews the current branch of this TheAlgorithms/Python fork against CONTRIBUTING.md, AGENTS.md and the PR template before a pull request is opened. Use after the change is committed and before running .claude/scripts/open_fork_pr.py.
tools: Read, Grep, Glob, Bash
---

You are a strict reviewer for a contribution to a fork of TheAlgorithms/Python.
You run in your own context: you see only the diff and the rule files, not the
conversation that produced the change. Do not edit any file.

## Inputs to read first

1. `CONTRIBUTING.md` and `AGENTS.md` in the repository root.
2. `.github/pull_request_template.md`.
3. The change: `git diff --stat upstream/master...HEAD` and
`git diff upstream/master...HEAD`.
4. The issue number you were given, and its rules if the caller pasted them.

## Checks (report each as PASS or FAIL with one line of evidence)

- Exactly one algorithm file changed (files under `tests/` don't count).
- Code and its doctests are not both changed, unless the issue requires tests.
- Every function parameter and return value has a type hint.
- Every function has at least one doctest.
- Algorithm behaviour is unchanged when the issue says so: existing doctest
expected outputs are untouched.
- Filenames are lowercase snake_case; names follow PEP 8.
- No `print()`/`input()` added to algorithm functions.
- Run and paste the real tail of each command (never invent output):
- `uvx ruff check <files>` and `uvx ruff format --check <files>`
- `uv run --with pytest pytest -q --doctest-modules <files>`
- `uvx ty check <files>`
- The PR will target the fork: `git remote get-url origin` is not
TheAlgorithms.

## Output

1. The PASS/FAIL table.
2. A verdict: `READY` or `NOT READY` with the blocking items.
3. If READY, a filled copy of `.github/pull_request_template.md`:
- tick every box that is true (`* [x]`), leave the rest unticked;
- add a short "Describe your change" paragraph above the boxes;
- reference a tracking issue as `Part of #N` (no closing keyword);
use `Fixes #N` only for an issue this PR fully resolves.
32 changes: 32 additions & 0 deletions .claude/commands/contribute.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
description: Contribute a fix for a TheAlgorithms/Python issue to this fork, from sync to pull request
argument-hint: <issue-number> <file-path>
---

Contribute to issue #$1 by changing `$2`. Follow `CONTRIBUTING.md` and
`AGENTS.md` throughout. The pull request goes to this fork only.

1. **Guard the target.** Run `git remote get-url origin`. Stop if it points at
TheAlgorithms. Make sure an `upstream` remote exists
(`git remote add upstream https://github.com/TheAlgorithms/Python.git`).
2. **Sync the fork.** `git fetch upstream`, then fast-forward `master` to
`upstream/master`.
3. **Check it is still needed.** Read issue #$1 and the current `$2` on
master. If master already fixes it, stop and report that instead of
duplicating work (CONTRIBUTING.md forbids identical implementations).
4. **Branch.** `git switch -c <short-descriptive-name>` from `master`.
5. **Change one file.** Edit `$2` only (plus `tests/` if the issue asks for
tests). Keep the diff minimal and behaviour unchanged unless the issue is a
bug fix. Never edit doctest output to make it pass.
6. **Verify.** Run `uvx ruff check`, `uvx ruff format --check`,
`uv run --with pytest pytest -q --doctest-modules $2`, and `uvx ty check $2`.
Fix the root cause of any failure.
7. **Commit.** Message: `<area>: <what changed>`, body explains why and ends
with `Part of #$1` (tracking issue) or `Fixes #$1` (fully resolved).
8. **Review in isolation.** Ask the `contributing-reviewer` sub-agent to review
the branch for issue #$1. If it says NOT READY, fix and repeat from step 6.
9. **Open the PR.** Save the reviewer's filled template to `.git/PR_BODY.md`
(inside `.git`, so it is never committed), then run
`python .claude/scripts/open_fork_pr.py --title "<commit subject>" --body-file .git/PR_BODY.md --dry-run`.
Show the user the dry run, and run it again without `--dry-run` only after
they approve.
228 changes: 228 additions & 0 deletions .claude/scripts/open_fork_pr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
"""
Open a pull request for the current branch *inside the contributor's fork*.

Lab 6 rule: contributions go to the fork, never to TheAlgorithms/Python.
`gh pr create` run from a fork targets the upstream repository by default, so
this script always passes an explicit `--repo <fork owner>/<repo>` and refuses
to run when that would point at TheAlgorithms.

Before pushing it enforces the CONTRIBUTING.md / AGENTS.md rules that a robot
can check:
* not on master, clean working tree
* exactly one algorithm file changed (tests/ excluded), snake_case filename
* PR body has a checked box and no closing keyword aimed at a tracking issue
* ruff check, ruff format --check and doctests pass on the changed files

Usage (from the repository root):
python .claude/scripts/open_fork_pr.py --title "..." --body-file .git/PR_BODY.md
python .claude/scripts/open_fork_pr.py ... --dry-run # print, do not push
"""

# A standalone helper, not a package (INP001); it runs fixed git/uv/gh argument
# lists without a shell, so the subprocess warnings do not apply (S603, S607).
# ruff: noqa: INP001, S603, S607

from __future__ import annotations

import argparse
import re
import shutil
import subprocess
import sys
from pathlib import Path

UPSTREAM_OWNER = "TheAlgorithms"
# Tracking issues must be referenced with "Part of", never closed by a PR.
TRACKING_ISSUES = {15187, 15234}
CHECKED_BOX = re.compile(r"^\s*[*-]\s*\[x\]", re.IGNORECASE | re.MULTILINE)
CLOSING_KEYWORD = re.compile(
r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#(\d+)", re.IGNORECASE
)
SNAKE_CASE_FILE = re.compile(r"^[a-z0-9_]+\.py$")


def parse_owner_repo(remote_url: str) -> tuple[str, str]:
"""
Return (owner, repository) from a GitHub remote URL.

>>> parse_owner_repo("https://github.com/NEHoward/Python.git")
('NEHoward', 'Python')
>>> parse_owner_repo("git@github.com:NEHoward/Python.git")
('NEHoward', 'Python')
>>> parse_owner_repo("https://gitlab.com/someone/Python")
Traceback (most recent call last):
...
ValueError: not a GitHub remote: https://gitlab.com/someone/Python
"""
match = re.search(r"github\.com[:/]([^/]+)/([^/]+?)(?:\.git)?/?$", remote_url)
if match is None:
msg = f"not a GitHub remote: {remote_url}"
raise ValueError(msg)
return match.group(1), match.group(2)


def check_target(owner: str) -> list[str]:
"""
Refuse any pull request whose base repository is the upstream project.

>>> check_target("NEHoward")
[]
>>> check_target("TheAlgorithms")
['origin points at TheAlgorithms: this lab must not contribute upstream']
"""
if owner.lower() == UPSTREAM_OWNER.lower():
return [
f"origin points at {UPSTREAM_OWNER}: this lab must not contribute upstream"
]
return []


def check_changed_files(changed_files: list[str]) -> list[str]:
"""
Apply the one-algorithm-file-per-PR and filename rules.

>>> check_changed_files(["sorts/power_sort.py"])
[]
>>> check_changed_files(["sorts/quick_sort.py", "tests/test_sorts.py"])
[]
>>> check_changed_files([])
['branch has no changes against origin/master']
>>> check_changed_files(["sorts/a_sort.py", "maths/b_math.py"])
['2 algorithm files changed: AGENTS.md allows one per PR']
>>> check_changed_files(["sorts/Bad-Name.py"])
['filename is not lowercase snake_case: sorts/Bad-Name.py']
"""
if not changed_files:
return ["branch has no changes against origin/master"]
problems = []
python_files = [path for path in changed_files if path.endswith(".py")]
algorithm_files = [path for path in python_files if not path.startswith("tests/")]
if len(algorithm_files) > 1:
problems.append(
f"{len(algorithm_files)} algorithm files changed: "
"AGENTS.md allows one per PR"
)
problems.extend(
f"filename is not lowercase snake_case: {path}"
for path in python_files
if not SNAKE_CASE_FILE.match(Path(path).name)
)
return problems


def check_body(body: str) -> list[str]:
"""
Check the PR description against the repository's PR template rules.

>>> check_body("* [x] Fix a bug\\nPart of #15234")
[]
>>> check_body("* [ ] Fix a bug")
['no checked box: algorithms-keeper closes PRs without one']
>>> check_body("* [x] typing\\nFixes #15234")
['closing keyword on tracking issue #15234: write "Part of #15234"']
>>> check_body("* [x] bug fix\\nFixes #10")
[]
"""
problems = []
if not CHECKED_BOX.search(body):
problems.append("no checked box: algorithms-keeper closes PRs without one")
for issue_number in CLOSING_KEYWORD.findall(body):
if int(issue_number) in TRACKING_ISSUES:
problems.append(
f"closing keyword on tracking issue #{issue_number}: "
f'write "Part of #{issue_number}"'
)
return problems


def git(*args: str) -> str:
"""Run a git command and return its stripped standard output."""
result = subprocess.run(["git", *args], capture_output=True, text=True, check=True)
return result.stdout.strip()


def run_quality_checks(changed_files: list[str]) -> list[str]:
"""Run ruff and doctests on the changed Python files; return failures."""
python_files = [path for path in changed_files if path.endswith(".py")]
if not python_files:
return []
commands = [
["uvx", "ruff", "check", *python_files],
["uvx", "ruff", "format", "--check", *python_files],
[
"uv",
"run",
"--with",
"pytest",
"pytest",
"-q",
"--doctest-modules",
*python_files,
],
]
failures = []
for command in commands:
print("$", " ".join(command))
if subprocess.run(command, check=False).returncode != 0:
failures.append(f"check failed: {' '.join(command[:4])}")
return failures


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[1])
parser.add_argument("--title", required=True)
parser.add_argument("--body-file", required=True, type=Path)
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--skip-checks", action="store_true")
args = parser.parse_args()

branch = git("rev-parse", "--abbrev-ref", "HEAD")
owner, repository = parse_owner_repo(git("remote", "get-url", "origin"))
problems = check_target(owner)
if branch in {"master", "main"}:
problems.append("you are on master: create a feature branch first")
if git("status", "--porcelain", "--untracked-files=no"):
problems.append("working tree has uncommitted changes")

# The PR base is the fork's master, so diff against it: the tooling commits
# on master stay out of the PR and only this branch's work is checked.
try:
git("fetch", "--quiet", "origin", "master")
except subprocess.CalledProcessError:
print("warning: could not fetch origin; using the local origin/master")
base = git("merge-base", "HEAD", "origin/master")
changed_files = git("diff", "--name-only", base, "HEAD").splitlines()
problems += check_changed_files(changed_files)
problems += check_body(args.body_file.read_text(encoding="utf-8"))
if not args.skip_checks:
problems += run_quality_checks(changed_files)

if problems:
print("\nNot opening a PR:")
for problem in problems:
print(f" - {problem}")
return 1

fork = f"{owner}/{repository}"
push = ["git", "push", "-u", "origin", branch]
create_pr = [
"gh", "pr", "create", "--repo", fork, "--base", "master",
"--head", branch, "--title", args.title, "--body-file", str(args.body_file),
] # fmt: skip
compare_url = f"https://github.com/{fork}/compare/master...{branch}?expand=1"
print(f"\nChanged files: {', '.join(changed_files)}")
print(f"PR target: {fork} (master <- {branch})")
if args.dry_run:
print("dry run:", " ".join(push))
print("dry run:", " ".join(create_pr))
return 0

subprocess.run(push, check=True)
if shutil.which("gh") is None:
print(f"gh is not installed. Open the PR here:\n {compare_url}")
return 0
return subprocess.run(create_pr, check=False).returncode


if __name__ == "__main__":
sys.exit(main())
18 changes: 18 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Fork of TheAlgorithms/Python (CS440 Lab 6)

Follow the repository's own rules: @CONTRIBUTING.md and @AGENTS.md

## Fork rules

- Pull requests target this fork (`origin`), never TheAlgorithms/Python.
Do not comment on, claim, or open anything in the upstream repository.
- `upstream` is read-only: fetch from it to sync, never push to it.
- Agent tooling lives on `master` only. Feature branches must contain just the
one algorithm file being changed, so the PR diff stays one file.

## Workflow

- `/contribute <issue> <file>` runs the full flow (`.claude/commands/contribute.md`).
- `contributing-reviewer` checks a branch against the rules in its own context.
- `.claude/scripts/open_fork_pr.py` checks the rules a script can enforce, then
pushes and opens the PR against the fork. Run it with `--dry-run` first.
23 changes: 14 additions & 9 deletions sorts/power_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,16 @@
"""

from collections.abc import Callable, Iterable
from typing import Any
from typing import Any, Protocol


def _find_run[T](
arr: list[T], start: int, end: int, key: Callable[[Any], Any] | None = None
class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...
def __le__(self, other: Any, /) -> bool: ...


def _find_run[T: Comparable](
arr: list[T], start: int, end: int, key: Callable[[T], Comparable] | None = None
) -> int:
"""
Detect a run (ascending or descending sequence) starting at 'start'.
Expand Down Expand Up @@ -132,12 +137,12 @@ def _node_power(total_length: int, b1: int, n1: int, b2: int, n2: int) -> int:
return power


def _merge[T](
def _merge[T: Comparable](
arr: list[T],
start1: int,
end1: int,
end2: int,
key: Callable[[Any], Any] | None = None,
key: Callable[[T], Comparable] | None = None,
) -> None:
"""
Merge two adjacent sorted runs in-place using auxiliary space.
Expand Down Expand Up @@ -194,10 +199,10 @@ def _merge[T](
k += 1


def power_sort[T](
def power_sort[T: Comparable](
collection: Iterable[T],
*,
key: Callable[[Any], Any] | None = None,
key: Callable[[T], Comparable] | None = None,
reverse: bool = False,
) -> list[T]:
"""
Expand Down Expand Up @@ -281,7 +286,7 @@ def power_sort[T](
if key:
original_key = key

def reverse_key(element: Any) -> Any:
def reverse_key(element: T) -> Comparable:
"""
Reverse key function for numeric values.

Expand All @@ -305,7 +310,7 @@ def reverse_key(element: Any) -> Any:
needs_final_reverse = True
else:

def reverse_cmp(element: Any) -> Any:
def reverse_cmp(element: T) -> Comparable:
"""
Reverse comparison function for numeric values.

Expand Down
Loading