TheAlgorithms/Python
github.com/TheAlgorithms/Python ↗ · 1697 files · 5.6 MB
The Algorithms - Python All algorithms implemented in Python - for education 📚 Implementations are for learning purposes only.
Overview
TheAlgorithms/Python is a large, flat collection of ~1,500 self-contained educational algorithm implementations in Python, organized by topic into ~45 top-level directories (sorts/, graphs/, maths/, ciphers/, project_euler/, etc.). It is not a deployable application — each file is an independent, doctest-driven module aimed at learners, and the project's real 'system' is its CI machinery: pytest running doctests across the whole tree on free-threaded Python 3.14t, ruff linting, an informational ty type-check, a SHA-256 answer oracle for Project Euler solutions, and bots/workflows that regenerate DIRECTORY.md and docs. Contributions are gated by strict conventions (doctests, type hints, snake_case filenames, one algorithm per PR) enforced by GitHub Actions and the algorithms-keeper bot.
System map
There is no runnable service or package entrypoint — the repo is a flat namespace of independent algorithm modules, declared as a 'virtual' project (no [build-system] in pyproject.toml) so `uv sync` installs only dependencies. The de-facto runtime is CI: eight GitHub Actions workflows gate PRs (build, ruff, ty, project_euler, sphinx, directory_writer, hacktoberfest_prep, devcontainer_ci). Tooling lives in scripts/ (directory generation, filename validation, Euler answer validation, PR janitor shell scripts). Storage is limited to checked-in artifacts: DIRECTORY.md (generated index), scripts/project_euler_answers.json (hashed answers), uv.lock, and docs/hacktober_2026_prep.md (bot-maintained tracker). External integrations are GitHub's API (gh CLI, GITHUB_TOKEN), GitHub Pages for Sphinx docs, and incidental web scraping inside web_programming/ modules.
- pyproject.toml declares project 'thealgorithms-python' v0.0.1 with requires-python >=3.14 and no [build-system] table, so uv treats the repo as a virtual project and installs only dependencies — it is never built as a wheel.
- The interpreter target is free-threaded CPython 3.14t, pinned via .python-version (contents '3.14t'); classifiers advertise Python 3.14/3.15 and 'Free Threading :: 2 - Beta'.
- Dependencies (numpy, scipy, pandas, scikit-learn, keras, matplotlib, pillow, sympy, httpx2, etc.) are managed by uv with a checked-in uv.lock; there is intentionally no requirements.txt.
- opencv-python and qiskit are quarantined into optional dependency groups 'cv' and 'quantum' because they lack free-threaded 3.14t wheels, and the corresponding test trees are --ignore'd in CI.
- Eight workflows in .github/workflows/ form the entire build/deploy pipeline: build.yml (pytest+coverage), ruff.yml (lint gate), ty.yml (informational type check), project_euler.yml (Euler doctests + answer validation), sphinx.yml (docs→GitHub Pages), directory_writer.yml (regenerate DIRECTORY.md on push), hacktoberfest_prep.yml (daily tracker bot), devcontainer_ci.yml.
- scripts/ is the only 'application code' layer: build_directory_md.py generates DIRECTORY.md, validate_filenames.py enforces naming, validate_solutions.py is the Euler oracle, hacktoberfest_prep_update.py and pr_file_map.py are maintainer bots, and close_pull_requests_with_*.sh are janitor scripts.
- scripts/project_euler_answers.json is the persistent store of expected Project Euler answers as SHA-256 hex digests, loaded at module import time by validate_solutions.py.
- DIRECTORY.md is a fully generated artifact — build_directory_md.py walks the tree and prints a nested Markdown index, and directory_writer.yml regenerates and force-pushes it on every push; CONTRIBUTING.md forbids editing it by hand.
- Documentation deployment is Sphinx + sphinx-autoapi + myst-parser: docs/conf.py enumerates 43 algorithm dirs in autoapi_dirs and sphinx.yml builds docs/_build/html and deploys to GitHub Pages on non-PR events.
- Local dev tooling is uv + pre-commit: .pre-commit-config.yaml wires ruff-check, ruff-format, codespell, pyproject-fmt, rumdl, auto-walrus, uv-lock, validate-pyproject, and a local validate-filenames hook.
- A devcontainer (.devcontainer/devcontainer.json, Dockerfile, post_install) and .gitpod.yml provide reproducible contributor environments; devcontainer_ci.yml builds it on changes.
- Each algorithm directory is a self-contained namespace (typically <topic>/<file>.py plus __init__.py); modules do not import each other across directories in general, so there is no internal package graph to map. (inferred)
Feature catalog
'Features' here are per-topic algorithm collections rather than product features: ~45 directories covering classic CS domains (sorts, searches, graphs, data_structures, dynamic_programming, ciphers, strings, maths), applied domains (machine_learning, neural_network, computer_vision, digital_image_processing, physics, electronics, financial, geodesy), curiosities (fractals, cellular_automata, fuzzy_logic, genetic_algorithm, quantum), a 344-file project_euler/ tree with a strict solution() contract, and web_programming/ scrapers that hit live third-party sites. Every module is directly runnable via its __main__ block and self-testing via doctests.
- sorts/ contains ~60 comparison and non-comparison sorts; sorts/bubble_sort.py alone ships bubble_sort_iterative and bubble_sort_recursive behind a shared Comparable Protocol and exercises a timing benchmark in its __main__ block.
- project_euler/ holds per-problem packages problem_NNN/ with multiple solN.py variants, each exposing a solution() function whose default arguments answer the problem (e.g. problem_001/sol1.py solution(n: int = 1000)).
- web_programming/ is a set of live scrapers/API clients: current_stock_price.py fetches Yahoo Finance HTML and parses a data-testid span with BeautifulSoup; fetch_anime_and_play.py scrapes gogoanime2.org search/episode/download URLs using fake-useragent.
- Other web_programming modules cover Hacker News, IMDb top-250 CSV export, COVID stats via XPath, GitHub info, currency conversion, Slack messages, reCAPTCHA verification, Reddit, NASA data, and Google result crawling — each a standalone network client.
- data_structures/ (144 files) implements linked lists, stacks/queues, hash maps, binary trees, kd-trees, suffix trees, tries, disjoint sets, and hashing — several with dedicated tests/ subdirectories (e.g. hashing/tests/test_hash_map.py, kd_tree/tests/test_kdtree.py).
- maths/ (217 files) is the largest non-Euler domain — primality tests, factorials, number theory, geometry helpers — with sibling test files like test_prime_check.py and test_factorial.py alongside implementations.
- file_transfer/send_file.py + receive_file.py demonstrate raw TCP socket file transfer on port 12312, with a testing flag so tests/test_send_file.py can exercise one accept loop.
- machine_learning/ and neural_network/ implement algorithms from scratch (linear regression, sequential minimal optimization for SVM, LSTM prediction, input_data MNIST loader) rather than being thin wrappers, per CONTRIBUTING.md's 'add unique value' rule.
- graphs/ (69 files) covers traversal, shortest paths (Floyd-Warshall, Johnson), minimum spanning trees (Kruskal, Prim), and flow networks, with a graphs/tests/ subdirectory of pytest modules.
- ciphers/ (56 files) implements classical and modern ciphers; hashes/enigma_machine.py is one of a few files granted a per-file ruff ignore (BLE001 blind-except) in pyproject.toml.
- quantum/q_fourier_transform.py is the single module importing qiskit; it is skipped in the 3.14t CI run because qiskit re-enables the GIL under free threading.
- digital_image_processing/ is almost entirely cv2-based and is excluded wholesale from the free-threaded test run until a cp314t opencv wheel ships.
Data flow
Because there is no service, 'data flow' means contributor/CI data flow. Inputs are algorithm modules (pure functions with doctests) and repo metadata. pytest --doctest-modules imports every module and runs embedded examples, feeding a coverage report; Project Euler answers flow through importlib-loaded modules' solution() into a SHA-256 comparison against a checked-in JSON oracle; DIRECTORY.md flows from an os.walk of the tree into a force-pushed commit; and the hacktoberfest bot flows GitHub API data into a tracked markdown file and a rolling PR. Output boundaries are stdout/CI logs, generated markdown files, and a GitHub Pages site.
- pytest is configured via [tool.pytest] ini_options with --doctest-modules, --durations=10, --showlocals and a 'mat_ops' marker; the build workflow runs it under pytest-run-parallel with --iterations=8 and --parallel-threads=auto to flush out GIL-dependent code.
- Coverage omits .env/* and project_euler/* and sorts the report by coverage percentage; the build job emits --cov-report=term-missing:skip-covered --cov=. .
- Euler validation flow: collect_solution_file_paths() picks either PR-added sol*.py files (via GITHUB_EVENT_PATH → GitHub API /files) or all of project_euler/; convert_path_to_module() exec_module's each file; test_project_euler calls solution(), SHA-256-hashes the stringified answer, and asserts equality with PROBLEM_ANSWERS[problem_number].
- DIRECTORY.md generation flow: good_file_paths() os.walks the repo skipping dot-dirs/venv/scripts/__init__.py, yields .py/.ipynb paths, print_directory_md() sorts them and prints a numbered table of contents plus nested bullet links via print_path()/md_prefix()/md_anchor().
- directory_writer.yml pipes build_directory_md.py stdout through `tee DIRECTORY.md`, commits as the actor, and force-pushes — so the generated file is an output boundary written back into the repo by automation.
- hacktoberfest_prep_update.py reads docs/hacktober_2026_prep.md, parses tracked rows with ROW_RE (`N. [ ] #PR ...`), queries the GitHub REST API through a single httpx2.AsyncClient at CONCURRENCY=5, ticks merged/closed PRs, and rewrites the '## Automated statistics' section in place.
- The hacktoberfest workflow deliberately separates dry-run (push/PR events show a git diff only) from persistence (scheduled/manual runs commit to a rolling branch chore/hacktoberfest-2026-prep-refresh and open/update one PR via gh), because master is protected.
- Sphinx docs flow: docs/conf.py loads project metadata from pyproject.toml via tomllib, autoapi_dirs lists 43 source trees to scan, sphinx-build -c docs . docs/_build/html produces the site, upload-pages-artifact + deploy-pages publish to GitHub Pages.
- Web-scraper modules are input boundaries to the live internet: current_stock_price.py builds a Yahoo Finance URL from a symbol and returns parsed text; no caching, rate limiting, or schema validation exists — output is whatever BeautifulSoup finds.
- Individual files declare their own PEP-723 inline script metadata (`# /// script ... dependencies`) so they can be run standalone with uv/uvx without the full project env (e.g. current_stock_price.py, validate_solutions.py).
- validate_filenames.py reuses good_file_paths() from build_directory_md.py and exits non-zero listing files with uppercase, spaces, hyphens, or no parent directory — filename hygiene is enforced as data flowing through the pre-commit local hook.
- pr_file_map.py is a maintainer-facing flow: it shells out to `gh` to list open PRs, maps files touched per PR, and emits a Markdown report that isolates DIRECTORY.md conflicts into their own section.
Behavior traces
Three flows characterize the system. (1) PR validation: a contributor push triggers ruff, then the build job syncs uv deps on 3.14t and runs pytest-run-parallel doctests across the tree with a long --ignore list, emitting coverage; ty runs non-blocking in parallel; project_euler changes additionally trigger doctest+answer validation. (2) Merge/push: directory_writer regenerates DIRECTORY.md and force-pushes; sphinx rebuilds and deploys Pages. (3) Euler answer check: pytest parametrizes over solution files, imports each with importlib, calls solution(), hashes, compares to JSON. A fourth operational flow is the daily hacktoberfest tracker refresh.
- PR flow step order: actions/checkout → setup-uv (cache on uv.lock) → setup-python from .python-version (3.14t, prereleases allowed) → conditional apt install libhdf5-dev for keras on pre-release Python → `uv sync --group=test` → `uv run --with=pytest-run-parallel pytest ...` → on success regenerate DIRECTORY.md via tee.
- The pytest invocation ignores 13 paths (cv2-dependent computer_vision files, digital_image_processing/, tensorflow/qiskit/MNIST-dependent modules, network-bound web_programming files, project_euler/, docs/conf.py, validate_solutions.py) before running doctests with coverage.
- Ruff gate: ruff.yml runs `uvx ruff check --output-format=github .` on push/PR to master using pyproject.toml's lint.select list of ~45 rule families (target py314), with a long lint.ignore list of deferred FIX ME/DO NOT FIX rules.
- ty type-check is advisory: workflow sets continue-on-error: true and invokes `ty check --exit-zero` pinned to regular-GIL Python 3.14, emitting ::error annotations without failing; pyproject [tool.ty] pre-ignores a dozen rule kinds as the baseline is cleaned.
- Euler CI trace: project_euler.yml is path-filtered to project_euler/**, the workflow file, and validate_solutions.py; job 1 runs `pytest --doctest-modules --cov=project_euler/ project_euler/`, job 2 runs `pytest scripts/validate_solutions.py` with GITHUB_TOKEN.
- Inside validate_solutions: at import time PROBLEM_ANSWERS is loaded from scripts/project_euler_answers.json; collect_solution_file_paths() → all_solution_file_paths() iterates problem_* dirs skipping files starting with '_' or 'test'; parametrized test_project_euler → convert_path_to_module → spec.loader.exec_module → module.solution() → sha256(answer) == expected.
- DIRECTORY.md trace on push: directory_writer.yml → checkout fetch-depth:0 → setup-python → `scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md` → git config actor → commit -am 'updating DIRECTORY.md' || true → push --force HEAD:$GITHUB_REF || true.
- build_directory_md.py print order: good_file_paths() yields sorted paths → a numbered 'Table of Contents' of top-level sections with md_anchor() slugs → print_path() emits '##' headings for new top dirs and nested bullets → each file becomes a titled link with underscores→spaces and %20-escaped URLs.
- Hacktoberfest bot trace (scheduled): checkout → pip install httpx2 → python scripts/hacktoberfest_prep_update.py (exit code captured, not fatal) → on schedule/dispatch, diff check docs/hacktober_2026_prep.md → gh auth setup-git → switch -c rolling branch → force-push → gh pr create if none open → propagate script exit code.
- The prep script intentionally exits non-zero on/after 2026-10-01 (HACKTOBERFEST_START) so the workflow fails loudly as a retirement signal; transient API failures raise BestEffortError which callers degrade rather than fail.
- Module self-run convention: algorithm files end with `if __name__ == '__main__':` calling doctest.testmod() and/or printing solution() results — e.g. bubble_sort.py runs a 10k-iteration timeit benchmark comparing iterative vs recursive.
- Devcontainer trace: devcontainer_ci.yml only triggers on .devcontainer/** or its own workflow path, and runs devcontainers/ci@v0.3 with push:never and runCmd 'true' — a smoke test that the image builds.
Testing signals
The dominant test mechanism is doctests: pytest runs with --doctest-modules across the entire repo, and CONTRIBUTING/AGENTS require every function to carry passing doctests. A minority of modules have real pytest test files — either colocated (maths/test_*.py) or in per-domain tests/ subdirectories (data_structures, graphs, knapsack, geometry, divide_and_conquer, file_transfer) plus a top-level tests/test_sorts.py battery. Project Euler has a dedicated hashed-answer oracle. Coverage is reported but project_euler is excluded; many files are excluded from the 3.14t run entirely via --ignore flags.
- pytest config sets --doctest-modules, --durations=10, --showlocals globally, so every docstring example in every .py file is executed as a test in CI.
- tests/test_sorts.py is a shared contract harness: it parametrizes ~20 general-purpose comparison sorts against a common battery and documents which sorts are deliberately excluded (counting/radix/pigeon integer-only, stalin/wiggle not fully sorting, etc.).
- Dedicated pytest files exist in pockets: data_structures/{hashing,kd_tree,suffix_tree}/tests/, graphs/tests/, knapsack/tests/, geometry/tests/, divide_and_conquer/tests/, file_transfer/tests/, and colocated maths/test_*.py — most of the repo relies solely on doctests.
- scripts/validate_solutions.py is itself a pytest module: test_project_euler is parametrized over discovered solution paths and asserts the SHA-256 of str(solution()) matches the stored digest, so Euler correctness is verified without exposing plaintext answers.
- The build runs pytest under pytest-run-parallel with --iterations=8 --parallel-threads=auto --ignore-gil-enabled on free-threaded 3.14t, actively probing thread-safety of pure-Python algorithms while tolerating GIL-re-enabling wheels.
- Coverage is collected (--cov=. with term-missing report) but project_euler/* and .env/* are omitted from the report; there is no coverage threshold gate.
- Thirteen paths are excluded from the test run via --ignore flags — including the whole digital_image_processing/ tree, project_euler/ (tested in its own workflow), and network-dependent web_programming files — so 'CI green' does not mean those files ran.
- Doctest conventions include exception tests (doctest: +IGNORE_EXCEPTION_DETAIL for TypeError on mixed-type input) and randomized-sample assertions (random.sample inputs compared to sorted()), which make doctests double as property-ish tests.
- Live-network tests exist: current_stock_price.py's doctests call stock_price('GOOG') expecting a float-parseable string and 'EEEE' expecting an error string — inherently flaky and excluded from CI.
- Static checks act as tests: ruff.yml gates on `ruff check`, pre-commit runs ruff-format/codespell/validate-filenames/uv-lock, and ty runs informationally — no unit-test framework other than pytest+doctest is used.
- project_euler.yml runs pytest --doctest-modules --cov=project_euler/ only on PRs touching Euler paths (plus daily cron), so Euler doctests are validated separately from the main suite.
- There is no conftest.py anywhere in the repo — no shared fixtures; each test file is self-contained, consistent with the one-file-per-algorithm contribution model.
Risk map
Risks are mostly process/supply-chain and flaky-network rather than exploitable bugs in a running system (there is none). Notable: workflows that force-push and write to the repo with a token, web scrapers hitting live third-party sites inside doctests, a daily bot that consumes the shared 1000-req/hour GITHUB_TOKEN budget, a hash oracle that will hard-fail if any Euler module import has side effects, known-buggy code (an undefined variable in fetch_anime_and_play.py), and large intentional gaps in test coverage (cv2/qiskit/tf files ignored on 3.14t).
- fetch_anime_and_play.py references `anime_name` inside search_anime_episode_list's error message, but that variable is not defined in that scope — a latent NameError that only triggers when the episode list element is missing.
- directory_writer.yml force-pushes to the pushed ref using GITHUB_TOKEN embedded in the remote URL (x-access-token), and both commit and push end with `|| true` — failures are silently swallowed and a bad regeneration can overwrite the ref.
- hacktoberfest_prep.yml runs with contents:write and pull-requests:write permissions and uses `gh auth setup-git` to push a rolling branch; the workflow file itself documents that GITHUB_TOKEN is capped at 1000 requests/hour per repo shared across concurrent runs, making the daily job rate-limit-fragile.
- validate_solutions.py exec_module's arbitrary contributed Python files during CI — necessary for the design, but it means any module-level code in a submitted sol*.py executes in a job that holds GITHUB_TOKEN. (inferred)
- Web scrapers depend on live third-party DOM structure: current_stock_price.py matches span[data-testid='qsp-price'] on Yahoo Finance and fetch_anime_and_play.py targets a hard-coded BASE_URL 'https://ww7.gogoanime2.org' — both will break silently or flake on site changes/rotating pirate domains.
- file_transfer/send_file.py binds a listening TCP socket on port 12312 to the machine hostname and loops accept() forever unless testing=True; receive counterpart likewise — running it as a script is a permanently open unauthenticated file server.
- CI skips are a blind spot: digital_image_processing/, quantum/q_fourier_transform.py, tensorflow-dependent dynamic_programming/k_means_clustering_tensorflow.py, neural_network/input_data.py, and cv2 computer_vision files are never exercised on the 3.14t runner.
- Ruff config ignores dozens of rules marked 'FIX ME'/'DO NOT FIX' (B904 raise-from, PLW2901, RET505, S311 weak-random, SLF001 private-access, blind-except per-file ignores), so real bug classes are deliberately unenforced repo-wide.
- Ty checking is explicitly non-blocking (continue-on-error + --exit-zero) and [tool.ty] suppresses a dozen diagnostic kinds including unresolved-import/unresolved-attribute — type errors currently cannot fail CI.
- Several modules read input() interactively in __main__ blocks (e.g. fetch_anime_and_play.py prompts three times) and CONTRIBUTING.md discourages but permits input() with .strip() — scripts hang waiting on stdin if run non-interactively.
- Euler correctness depends on scripts/project_euler_answers.json staying in sync: test_project_euler indexes PROBLEM_ANSWERS[problem_number] with no missing-key handling, so a new problem dir without an answers entry raises KeyError, not a clean failure.
- blast-radius: a single bad commit to pyproject.toml (deps), .python-version, or a workflow affects every subsequent CI run for all PRs; conversely individual algorithm files are isolated and nearly impossible to damage each other. (inferred)
Extension points
The extension model is 'add a file': drop a snake_case .py module into an existing topic directory, give every function doctests + type hints + a reference URL, and CI/pytest auto-discovers it via --doctest-modules with zero registration. Project Euler has a stricter contract (problem_NNN dirs, solN.py files, one solution() entrypoint, an answers-JSON entry). Generated surfaces (DIRECTORY.md, Sphinx autoapi, coverage) pick up new files automatically; new top-level directories additionally require updating docs/conf.py autoapi_dirs. Optional dependency groups (cv, quantum, euler-validate, docs, test) are the seam for heavy new deps.
- Auto-discovery is the plugin mechanism: pytest --doctest-modules plus os.walk-based good_file_paths() mean a new .py file in any existing directory is tested and indexed with no registry edits.
- New top-level directories DO require manual registration: docs/conf.py's autoapi_dirs is a hardcoded list of 43 dirs, and CONTRIBUTING.md says avoid creating new directories anyway.
- Project Euler extension contract: create project_euler/problem_<NNN>/__init__.py + sol1.py (etc.) exposing solution() whose defaults yield the answer; module docstring must link the problem; answers are enforced by scripts/project_euler_answers.json.
- Per-domain tests/ subdirectories are the pattern for adding real pytest coverage beyond doctests (hashing/tests/, kd_tree/tests/, graphs/tests/, knapsack/tests/), discovered automatically by pytest.
- New third-party dependencies extend via pyproject.toml dependencies or an optional [dependency-groups] section; the uv-lock pre-commit hook regenerates uv.lock, and heavy/GIL-bound deps should follow the cv/quantum optional-group precedent plus a build.yml --ignore entry.
- PEP-723 inline script metadata (`# /// script`) is the lightweight seam for standalone runnable files needing extra deps without touching pyproject — used by web_programming scrapers and validate_solutions.py.
- Ruff per-file-ignores in pyproject.toml are the sanctioned escape hatch when a new file legitimately violates a rule (existing entries for BLE001, SIM115, SIM103).
- Pre-commit local hooks are the extension point for new repo-wide checks — validate-filenames is a `repo: local` hook entry-pointing to scripts/validate_filenames.py; new validators can be added the same way.
- Reusable Comparable Protocol + TypeVar pattern in sorts/bubble_sort.py is the house generic-typing idiom for container algorithms; new sorts should reuse it to satisfy the shared tests/test_sorts.py battery contract (return sorted list, comparable items).
- Maintainer automation extends via scripts/ + workflows: hacktoberfest_prep_update.py shows the pattern (httpx2 AsyncClient, GITHUB_TOKEN, TRACKER file rewrite, rolling-branch PR) reusable for new bots.
- GitHub Skills under .github/skills/ (code-review, new-pull-request, review-open-issue SKILL.md files) encode agent-facing contribution procedures — the repo's own extension surface for AI agents.
- The one-algorithm-per-PR rule plus 'identical implementations not allowed' in CONTRIBUTING.md defines the feature-addition boundary: variants of an existing algorithm must differ meaningfully (complexity, representation), matching the sol1..solN pattern in project_euler.
Contributor handoff
Read AGENTS.md and CONTRIBUTING.md first — they are the contract. Edits should be one file, one algorithm, minimal diff. The enforcement surface is: ruff check/format (uvx ruff), pytest doctests per file, snake_case lowercase filenames inside existing directories, type hints on all params/returns, and a checked checkbox in the PR template or algorithms-keeper auto-closes. Never touch DIRECTORY.md (bot-generated), never fabricate doctest output, and check build.yml's --ignore list before assuming a file is tested. Run `uvx pre-commit run --all-files` to replicate CI locally.
- AGENTS.md is the authoritative agent doc: mandates ruff (uvx ruff check/format), type hints on every parameter and return, ≥1 passing doctest per function, lowercase-underscore filenames, placement inside existing directories, and a reference URL for new algorithms.
- The single most common automated rejection: algorithms-keeper closes any PR whose 'Describe your change' section has no checked box — the template is .github/pull_request_template.md; always tick at least one box.
- Scope rules: one algorithm file per PR; never change code and its doctests in the same PR; keep diffs minimal and preserve existing style.
- Local verification commands: `uvx pre-commit run --all-files` for lint/format/hooks and `uvx pytest <dir>/<file>.py --doctest-modules` (or `uv run pytest`) for tests — there is no requirements.txt; deps come from pyproject.toml + uv.lock.
- Never edit DIRECTORY.md or README.md index sections by hand — DIRECTORY.md is regenerated and force-pushed by directory_writer.yml from scripts/build_directory_md.py output.
- Some directories/files are intentionally skipped in CI via --ignore in build.yml (cv2/qiskit/tf/network-bound files); check that list before assuming a file is exercised, and add new ignores there if a new heavy dep is introduced.
- Doctest honesty rule: never fabricate expected output — run the doctest and paste the real result; exception-testing uses `# doctest: +IGNORE_EXCEPTION_DETAIL`.
- Project Euler submissions have extra rules: read project_euler/README.md, use problem_NNN dir naming with __init__.py, expose solution() with the question input as default arg, and do not doctest the final answer (the sha256 oracle does that).
- Known trap: `uv sync` on free-threaded 3.14t cannot install opencv-python or qiskit (kept in optional groups); use `uv sync --group=test` like CI, and add --group=cv/--group=quantum only when needed.
- Files to read before editing any given area: the target algorithm file, AGENTS.md, CONTRIBUTING.md, and for Euler project_euler/README.md; for CI changes also pyproject.toml and the relevant workflow file. (inferred)
- Type checking with ty is informational only — agents should still add annotations (PR checklist requires them) but ty failures will not block merge; run `ty check <file>` locally per CONTRIBUTING.md.
- Ruff ignore-list traps: many style classes are globally suppressed (S101 assert allowed, S311 weak-random, B904) — matching repo style means not 'fixing' unrelated lint noise outside your file's diff.
Languages
| Language | Files | Share of source |
|---|---|---|
| Python | 1582 | 99% |
| Markdown | 37 | docs/config |
| YAML | 17 | docs/config |
| Shell | 7 | 0% |
| JSON | 3 | docs/config |
| TOML | 1 | 0% |
Start reading here
Probable source entrypoint: project_euler/ — inferred from the directory tree and manifest, not the upstream docs.
Source roots
project_euler/ (344 files) maths/ (217 files) data_structures/ (144 files)
Source layout — project_euler/
| Path | Files |
|---|---|
project_euler/problem_001/ | 8 |
project_euler/problem_006/ | 5 |
project_euler/problem_007/ | 4 |
project_euler/problem_008/ | 4 |
project_euler/problem_009/ | 5 |
project_euler/problem_030/ | 2 |
project_euler/problem_031/ | 3 |
project_euler/problem_036/ | 2 |
project_euler/problem_037/ | 2 |
project_euler/problem_038/ | 2 |
project_euler/problem_039/ | 2 |
project_euler/problem_052/ | 2 |
project_euler/problem_053/ | 2 |
project_euler/problem_054/ | 4 |
Repository structure
| Top-level path | Files |
|---|---|
project_euler/ | 344 |
maths/ | 217 |
data_structures/ | 144 |
graphs/ | 69 |
strings/ | 65 |
sorts/ | 62 |
ciphers/ | 56 |
dynamic_programming/ | 53 |
Docs found: AGENTS.mdCONTRIBUTING.mdLICENSE.mdREADME.mddocs/hacktober_2026_prep.md
Package
pyproject.toml — thealgorithms-python v0.0.1, 0 declared dependencies.
CI & config entrypoints
README.md— Repository readmeAGENTS.md— Agent instructions.github/workflows/ty.yml— GitHub Actions workflow.github/workflows/sphinx.yml— GitHub Actions workflow.github/workflows/hacktoberfest_prep.yml— GitHub Actions workflow.github/workflows/ruff.yml— GitHub Actions workflow.github/workflows/devcontainer_ci.yml— GitHub Actions workflow.github/workflows/directory_writer.yml— GitHub Actions workflow.github/workflows/project_euler.yml— GitHub Actions workflow.github/workflows/build.yml— GitHub Actions workflow
Structural health signals
Average score 6.8/10 across 96 analyzed source files; 20 hotspots surfaced.
machine_learning/loss_functions.py— 929 lines, score 5.7 (Large file, Deep nesting)machine_learning/sequential_minimum_optimization.py— 622 lines, score 5.9 (Large file, Deep nesting)scripts/hacktoberfest_prep_update.py— 449 lines, score 5.9 (Deep nesting, High churn)
These are deterministic review leads — size, churn, and structural signals — not proof of a bug in this project.
Recent history
52b9b913e08e2026-09-22 — refactor(maths): use direct iteration instead of index-based loops in persistence.py (#14767)a5f5f60cd5012026-09-22 — fix typo in binomial_distribution.py output (#14779)a0b2ef538a262026-09-22 — Fix incorrect doctest and improve log handling in num_digits functions (#13850)e2ada021591d2026-09-22 — chore: uv sync --upgrade + relock; make scripts/pr_file_map.py executable (#15398)7202e13f82672026-09-22 — Add t-SNE implementation and tests for dimensionality reduction (#13337)