Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- run: sudo apt-get update && sudo apt-get install -y libhdf5-dev
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v7
with:
enable-cache: true
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/devcontainer_ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: devcontainers/ci@v0.3
with:
push: never
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/directory_writer.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ jobs:
directory_writer:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
with:
fetch-depth: 0
- uses: actions/setup-python@v6
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/project_euler.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
libxml2-dev libxslt-dev
libhdf5-dev
libopenblas-dev
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v7
- uses: actions/setup-python@v6
with:
Expand All @@ -39,7 +39,7 @@ jobs:
libxml2-dev libxslt-dev
libhdf5-dev
libopenblas-dev
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v7
- uses: actions/setup-python@v6
with:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ruff.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v7
- run: uvx ruff check --output-format=github .
2 changes: 1 addition & 1 deletion .github/workflows/sphinx.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ jobs:
libxml2-dev libxslt-dev
libhdf5-dev
libopenblas-dev
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v7
- uses: actions/setup-python@v6
with:
Expand Down
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.15.9
rev: v0.15.20
hooks:
- id: ruff-check
- id: ruff-format
Expand All @@ -32,7 +32,7 @@ repos:
- tomli

- repo: https://github.com/tox-dev/pyproject-fmt
rev: v2.21.0
rev: v2.25.1
hooks:
- id: pyproject-fmt

Expand Down
4 changes: 4 additions & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,8 @@
* [Geometry](geometry/geometry.py)
* [Graham Scan](geometry/graham_scan.py)
* [Jarvis March](geometry/jarvis_march.py)
* [Ramer Douglas Peucker](geometry/ramer_douglas_peucker.py)
* [Segment Intersection](geometry/segment_intersection.py)
* Tests
* [Test Graham Scan](geometry/tests/test_graham_scan.py)
* [Test Jarvis March](geometry/tests/test_jarvis_march.py)
Expand Down Expand Up @@ -523,6 +525,7 @@
* [Graphs Floyd Warshall](graphs/graphs_floyd_warshall.py)
* [Greedy Best First](graphs/greedy_best_first.py)
* [Greedy Min Vertex Cover](graphs/greedy_min_vertex_cover.py)
* [Johnson](graphs/johnson.py)
* [Kahns Algorithm Long](graphs/kahns_algorithm_long.py)
* [Kahns Algorithm Topo](graphs/kahns_algorithm_topo.py)
* [Karger](graphs/karger.py)
Expand All @@ -543,6 +546,7 @@
* [Strongly Connected Components](graphs/strongly_connected_components.py)
* [Tarjans Scc](graphs/tarjans_scc.py)
* Tests
* [Test Johnson](graphs/tests/test_johnson.py)
* [Test Min Spanning Tree Kruskal](graphs/tests/test_min_spanning_tree_kruskal.py)
* [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py)

Expand Down
12 changes: 7 additions & 5 deletions bit_manipulation/binary_count_trailing_zeros.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ def binary_count_trailing_zeros(a: int) -> int:
>>> binary_count_trailing_zeros(4294967296)
32
>>> binary_count_trailing_zeros(0)
0
Traceback (most recent call last):
...
ValueError: Input value must be a positive integer
>>> binary_count_trailing_zeros(-10)
Traceback (most recent call last):
...
Expand All @@ -31,11 +33,11 @@ def binary_count_trailing_zeros(a: int) -> int:
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
if a < 0:
raise ValueError("Input value must be a positive integer")
elif isinstance(a, float):
if isinstance(a, float):
raise TypeError("Input value must be a 'int' type")
return 0 if (a == 0) else int(log2(a & -a))
if a < 0 or a == 0:
raise ValueError("Input value must be a positive integer")
return int(log2(a & -a))


if __name__ == "__main__":
Expand Down
184 changes: 184 additions & 0 deletions geometry/ramer_douglas_peucker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
"""
Ramer-Douglas-Peucker polyline simplification algorithm.

Given a sequence of 2-D points and a tolerance epsilon, the algorithm
reduces the number of points while preserving the overall shape of the curve.

Time complexity: O(n log n) average, O(n²) worst case
Space complexity: O(n)

References:
https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
"""

from __future__ import annotations

import math


def _euclidean_distance(
point_a: tuple[float, float],
point_b: tuple[float, float],
) -> float:
"""Return the Euclidean distance between two 2-D points.

>>> _euclidean_distance((0.0, 0.0), (3.0, 4.0))
5.0
>>> _euclidean_distance((1.0, 1.0), (1.0, 1.0))
0.0
"""
return math.hypot(point_b[0] - point_a[0], point_b[1] - point_a[1])


def _perpendicular_distance(
point: tuple[float, float],
line_start: tuple[float, float],
line_end: tuple[float, float],
) -> float:
"""Return the distance from *point* to the line **segment** between
*line_start* and *line_end*.

When the perpendicular projection of *point* onto the infinite line falls
within the segment, this equals the perpendicular distance to that line.
When the projection falls outside the segment, the distance to the nearest
endpoint is returned instead (projection clamped to [0, 1]).

This is the correct distance measure for the Ramer-Douglas-Peucker
algorithm: using the infinite-line distance can incorrectly discard points
whose projection lies beyond a segment endpoint.

>>> _perpendicular_distance((4.0, 0.0), (0.0, 0.0), (0.0, 3.0))
4.0
>>> # order of line_start and line_end does not affect the result
>>> _perpendicular_distance((4.0, 0.0), (0.0, 3.0), (0.0, 0.0))
4.0
>>> _perpendicular_distance((4.0, 1.0), (0.0, 1.0), (0.0, 4.0))
4.0
>>> _perpendicular_distance((2.0, 1.0), (-2.0, 1.0), (-2.0, 4.0))
4.0
>>> # projection falls outside the segment; distance to nearest endpoint
>>> round(_perpendicular_distance((0.0, 2.0), (1.0, 0.0), (3.0, 0.0)), 6)
2.236068
"""
px, py = point
ax, ay = line_start
bx, by = line_end
dx, dy = bx - ax, by - ay
seg_len_sq = dx * dx + dy * dy
if seg_len_sq == 0.0:
# line_start and line_end coincide; fall back to point-to-point distance
return _euclidean_distance(point, line_start)
# Project point onto the segment line, then clamp t to [0, 1] so the
# nearest point is always on the segment rather than the infinite line.
t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / seg_len_sq))
nearest_x = ax + t * dx
nearest_y = ay + t * dy
return math.hypot(px - nearest_x, py - nearest_y)


def ramer_douglas_peucker(
pts: list[tuple[float, float]],
epsilon: float,
) -> list[tuple[float, float]]:
"""Simplify a polyline using the Ramer-Douglas-Peucker algorithm.

Given a sequence of 2-D points and a maximum allowable deviation
*epsilon* (>= 0), returns a simplified list of points such that no
discarded point is farther than *epsilon* from the simplified polyline.

Parameters
----------
pts:
Ordered sequence of ``(x, y)`` points describing the polyline.
epsilon:
Maximum allowable distance of any discarded point from the
simplified polyline. Must be non-negative.

Returns
-------
list[tuple[float, float]]
Simplified list of ``(x, y)`` points. The first and last points of
*pts* are always preserved.

Raises
------
ValueError
If *epsilon* is negative.

References
----------
https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm

Examples
--------
>>> ramer_douglas_peucker([], epsilon=1.0)
[]
>>> ramer_douglas_peucker([(0.0, 0.0)], epsilon=1.0)
[(0.0, 0.0)]
>>> ramer_douglas_peucker([(0.0, 0.0), (1.0, 0.0)], epsilon=1.0)
[(0.0, 0.0), (1.0, 0.0)]
>>> # middle point is within epsilon - it is discarded
>>> ramer_douglas_peucker([(0.0, 0.0), (1.0, 0.1), (2.0, 0.0)], epsilon=0.5)
[(0.0, 0.0), (2.0, 0.0)]
>>> # middle point exceeds epsilon - it is kept
>>> ramer_douglas_peucker([(0.0, 0.0), (1.0, 1.0), (2.0, 0.0)], epsilon=0.5)
[(0.0, 0.0), (1.0, 1.0), (2.0, 0.0)]
>>> ramer_douglas_peucker([(0.0, 0.0), (1.0, 0.5), (2.0, 0.0)], epsilon=-1.0)
Traceback (most recent call last):
...
ValueError: epsilon must be non-negative, got -1.0
"""
if epsilon < 0:
msg = f"epsilon must be non-negative, got {epsilon!r}"
raise ValueError(msg)

if len(pts) < 3:
return list(pts)

# ---------------------------------------------------------------------------
# Iterative, stack-based implementation.
#
# The naive recursive approach copies sublists at every level via slicing
# (pts[:max_index+1] / pts[max_index:]), which is O(n) per call and makes
# the overall algorithm O(n²) in memory even for well-balanced splits. An
# explicit stack operating on index ranges avoids all copying and also
# eliminates the risk of hitting Python's recursion limit for long polylines.
# ---------------------------------------------------------------------------
n = len(pts)

# keep[i] is True when pts[i] must appear in the output.
keep: list[bool] = [False] * n
keep[0] = True
keep[-1] = True

# Stack of (start_index, end_index) pairs still to be examined.
stack: list[tuple[int, int]] = [(0, n - 1)]

while stack:
start, end = stack.pop()
if end - start < 2:
# Only one interior candidate at most; nothing to split further.
continue

# Find the interior point with the greatest distance to the segment.
max_dist = 0.0
max_index = start
for i in range(start + 1, end):
dist = _perpendicular_distance(pts[i], pts[start], pts[end])
if dist > max_dist:
max_dist = dist
max_index = i

if max_dist > epsilon:
keep[max_index] = True
stack.append((start, max_index))
stack.append((max_index, end))
# else: all interior points are within epsilon; discard them all.

return [pts[i] for i in range(n) if keep[i]]


if __name__ == "__main__":
import doctest

doctest.testmod()
Loading