Alnoms Library Reference
This reference is the single source of truth for the Alnoms industrial standard. All documentation below is generated deterministically from the sovereign source code.
𧬠Algorithms (alnoms.algorithms)
The algorithm pillar provides precision implementations for complex computational problems.
πΈοΈ Graph Theory
Graph Traversal Algorithms.
This module provides classes for traversing graphs and digraphs. It implements the standard "Algorithm Object" pattern: instantiate the class with a graph to run the algorithm, then query the object for results.
Classes:
| Name | Description |
|---|---|
- DepthFirstPaths |
Finds paths from a source vertex using DFS. |
- BreadthFirstPaths |
Finds shortest paths (unweighted) using BFS. |
- Topological |
Computes topological order for Directed Acyclic Graphs (DAGs). |
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Sections 4.1 and 4.2.
BreadthFirstPaths
Finds shortest paths (in terms of number of edges) from a source vertex 's' using Breadth First Search (BFS).
Time Complexity: O(V + E) Space Complexity: O(V)
Source code in src/alnoms/algorithms/graph/traversal.py
__init__(G, s)
Computes the BFS tree from source s.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
Graph
|
The graph to search. |
required |
s
|
int
|
The source vertex. |
required |
Source code in src/alnoms/algorithms/graph/traversal.py
dist_to(v)
Returns the number of edges in the shortest path from s to v.
has_path_to(v)
path_to(v)
Returns the shortest path from the source to v.
Source code in src/alnoms/algorithms/graph/traversal.py
DepthFirstPaths
Finds paths from a source vertex 's' to every other vertex using Depth First Search (DFS).
This is used to answer connectivity questions ("Is there a path from s to v?"). Paths found are NOT guaranteed to be the shortest.
Time Complexity: O(V + E) Space Complexity: O(V)
Source code in src/alnoms/algorithms/graph/traversal.py
__init__(G, s)
Computes the DFS tree from source s.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
Graph
|
The graph to search. |
required |
s
|
int
|
The source vertex. |
required |
Source code in src/alnoms/algorithms/graph/traversal.py
has_path_to(v)
path_to(v)
Returns a path from the source to v, or None if no such path exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The destination vertex. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Iterable[int]]
|
Iterable[int]: A sequence of vertices starting at s and ending at v. |
Source code in src/alnoms/algorithms/graph/traversal.py
Topological
Computes the Topological Sort of a Directed Acyclic Graph (DAG).
A topological sort is a linear ordering of vertices such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering.
If the graph has a cycle, no topological order exists.
Time Complexity: O(V + E)
Source code in src/alnoms/algorithms/graph/traversal.py
__init__(G)
Computes the topological order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
Digraph
|
The directed graph. |
required |
Source code in src/alnoms/algorithms/graph/traversal.py
has_order()
Returns True if the graph is a DAG (has a topological order).
Source code in src/alnoms/algorithms/graph/traversal.py
Shortest Path Algorithms.
This module provides algorithms for finding the shortest paths in edge-weighted directed graphs. It includes data structures for representing weighted directed graphs and implementation of standard shortest path algorithms.
Classes:
| Name | Description |
|---|---|
- DirectedEdge |
Represents a weighted edge in a directed graph. |
- EdgeWeightedDigraph |
Represents an edge-weighted directed graph. |
- DijkstraSP |
Computes shortest paths using Dijkstra's algorithm (non-negative weights). |
- BellmanFordSP |
Computes shortest paths using Bellman-Ford (handles negative weights). |
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 4.4.
BellmanFordSP
Bellman-Ford Shortest Path Algorithm.
Computes shortest paths from a single source vertex 's' to every other vertex in a digraph that may contain negative edge weights.
It detects negative cycles. If a negative cycle exists reachable from the source, shortest paths are undefined (or infinitely small).
Time Complexity: O(V * E) Space Complexity: O(V)
Source code in src/alnoms/algorithms/graph/shortest_path.py
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | |
__init__(G, s)
Computes the shortest paths from source s.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
EdgeWeightedDigraph
|
The graph. |
required |
s
|
int
|
The source vertex. |
required |
Source code in src/alnoms/algorithms/graph/shortest_path.py
dist_to(v)
has_negative_cycle()
Returns True if the graph contains a negative cycle reachable from the source.
has_path_to(v)
path_to(v)
Returns the shortest path from the source to vertex v.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The destination vertex. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Iterable[DirectedEdge]]
|
Optional[Iterable[DirectedEdge]]: A sequence of edges, or None if no path. |
Source code in src/alnoms/algorithms/graph/shortest_path.py
DijkstraSP
Dijkstra's Shortest Path Algorithm.
Computes the shortest path from a single source vertex 's' to every other vertex in an edge-weighted digraph where all edge weights are non-negative.
Time Complexity: O(E log V) Space Complexity: O(V)
Source code in src/alnoms/algorithms/graph/shortest_path.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
__init__(G, s)
Computes the shortest paths from source s.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
EdgeWeightedDigraph
|
The graph. |
required |
s
|
int
|
The source vertex. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the graph contains an edge with negative weight. |
Source code in src/alnoms/algorithms/graph/shortest_path.py
dist_to(v)
Returns the length of the shortest path from the source to vertex v. Returns infinity if no such path exists.
has_path_to(v)
path_to(v)
Returns the shortest path from the source to vertex v.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The destination vertex. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Iterable[DirectedEdge]]
|
Optional[Iterable[DirectedEdge]]: A sequence of edges, or None if no path. |
Source code in src/alnoms/algorithms/graph/shortest_path.py
DirectedEdge
Represents a weighted edge in a directed graph.
Immutable data type.
Source code in src/alnoms/algorithms/graph/shortest_path.py
weight
property
Returns the weight of the edge.
__init__(v, w, weight)
Initializes a directed edge from vertex v to vertex w with the given weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The source vertex. |
required |
w
|
int
|
The destination vertex. |
required |
weight
|
float
|
The weight of the edge. |
required |
Source code in src/alnoms/algorithms/graph/shortest_path.py
__str__()
from_vertex()
EdgeWeightedDigraph
Represents an edge-weighted directed graph.
Implemented using adjacency lists, where each list contains DirectedEdge objects.
Source code in src/alnoms/algorithms/graph/shortest_path.py
E()
V()
__init__(V)
Initializes an empty edge-weighted digraph with V vertices and 0 edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
V
|
int
|
The number of vertices. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If V is negative. |
Source code in src/alnoms/algorithms/graph/shortest_path.py
add_edge(e)
Adds the directed edge e to the digraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
e
|
DirectedEdge
|
The edge to add. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If endpoints are out of bounds. |
Source code in src/alnoms/algorithms/graph/shortest_path.py
adj(v)
Returns the edges incident from vertex v.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The source vertex. |
required |
Returns:
| Type | Description |
|---|---|
Iterable[DirectedEdge]
|
Iterable[DirectedEdge]: Edges starting at v. |
Source code in src/alnoms/algorithms/graph/shortest_path.py
edges()
Returns all edges in the digraph.
Returns:
| Type | Description |
|---|---|
Iterable[DirectedEdge]
|
Iterable[DirectedEdge]: All edges in the graph. |
Source code in src/alnoms/algorithms/graph/shortest_path.py
Minimum Spanning Tree (MST) Algorithms.
This module provides algorithms to find the MST of an edge-weighted graph. The MST is a subgraph that connects all vertices with the minimum possible total edge weight and no cycles.
Classes:
| Name | Description |
|---|---|
- KruskalMST |
Uses a Disjoint Set (Union-Find) to build the MST by merging sorted edges. efficient for sparse graphs. |
- LazyPrimMST |
Uses a Priority Queue to grow the MST from a starting vertex. |
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 4.3.
KruskalMST
Computes the Minimum Spanning Tree using Kruskal's Algorithm.
Logic: 1. Sort all edges by weight. 2. Add the smallest edge to the MST unless it creates a cycle. 3. Use Union-Find (DisjointSet) to detect cycles efficiently.
Time Complexity: O(E log E) Space Complexity: O(E)
Source code in src/alnoms/algorithms/graph/mst.py
__init__(G)
Computes the MST.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
EdgeWeightedGraph
|
The graph to process. |
required |
Source code in src/alnoms/algorithms/graph/mst.py
edges()
LazyPrimMST
Computes the Minimum Spanning Tree using the Lazy Prim's Algorithm.
Logic: 1. Start at vertex 0. 2. Add all edges connected to 0 to a Priority Queue (PQ). 3. Extract the minimum edge from PQ. 4. If the edge connects to a vertex not yet in the MST, add it. 5. Repeat until the MST is complete.
"Lazy" means we leave obsolete edges in the PQ and ignore them later (when we pop them and realize both endpoints are already visited).
Time Complexity: O(E log E) Space Complexity: O(E)
Source code in src/alnoms/algorithms/graph/mst.py
Network Flow Algorithms.
This module provides the Ford-Fulkerson algorithm for solving the max-flow min-cut problem in flow networks.
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 6.4.
FordFulkerson
Computes the maximum flow and minimum cut in a flow network.
This implementation uses the shortest augmenting path (Edmonds-Karp) approach via Breadth-First Search (BFS) to find paths in the residual graph, ensuring polynomial time complexity.
Source code in src/alnoms/algorithms/graph/flow.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | |
__init__(G, s, t)
Initializes the solver and computes the maximum flow from s to t.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
FlowNetwork
|
The flow network. |
required |
s
|
int
|
The source vertex. |
required |
t
|
int
|
The sink vertex. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If s or t are out of bounds or s == t. |
Source code in src/alnoms/algorithms/graph/flow.py
in_cut(v)
Returns true if vertex v is on the source side of the minimum cut.
A vertex is in the min-cut if it is reachable from the source in the residual graph after the max-flow has been computed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if v is in the source-side of the min-cut. |
Source code in src/alnoms/algorithms/graph/flow.py
value()
Returns the value of the maximum flow.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Total flow from source to sink. |
π Computational Math
Reductions and Flow Network Algorithms.
This module provides implementations of the Ford-Fulkerson algorithm for computing maximum flow and minimum cuts in flow networks, as well as reductions for problems like Bipartite Matching.
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 6.4.
BipartiteMatching
Solves the Maximum Bipartite Matching problem via reduction to Max-Flow.
Source code in src/alnoms/algorithms/math/reductions.py
__init__(adj, n, m)
Computes maximum matching in a bipartite graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adj
|
List[List[int]]
|
Adjacency list where adj[i] contains neighbors of vertex i in the first set. |
required |
n
|
int
|
Number of vertices in the first set (0 to n-1). |
required |
m
|
int
|
Number of vertices in the second set (0 to m-1). |
required |
Source code in src/alnoms/algorithms/math/reductions.py
FordFulkerson
Computes the maximum flow and minimum cut in a flow network.
Uses the shortest augmenting path (Edmonds-Karp) implementation to ensure polynomial time complexity.
Source code in src/alnoms/algorithms/math/reductions.py
__init__(G, s, t)
Initializes the Ford-Fulkerson solver and computes max flow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
FlowNetwork
|
The flow network to analyze. |
required |
s
|
int
|
The source vertex. |
required |
t
|
int
|
The sink vertex. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If s or t are out of bounds or s == t. |
Source code in src/alnoms/algorithms/math/reductions.py
in_cut(v)
Returns true if vertex v is on the source side of the minimum cut.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex to check. |
required |
Linear Programming and the Simplex Algorithm.
This module provides an implementation of the Simplex algorithm for solving standard-form linear programming maximization problems.
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 6.5.
Simplex
Simplex algorithm for solving linear programming maximization problems.
The problem is defined as: Maximize (c^T * x) subject to Ax <= b and x >= 0.
This implementation uses a tableau representation and Bland's Rule to avoid cycling in the presence of degeneracy.
Source code in src/alnoms/algorithms/math/simplex.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | |
__init__(a, b, c)
Initializes the Simplex solver and executes the optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
List[List[float]]
|
Constraint matrix (m x n). |
required |
b
|
List[float]
|
Right-hand side vector (m). |
required |
c
|
List[float]
|
Objective function coefficients (n). |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If b[i] < 0 (requires a Two-Phase Simplex, not covered here). |
Source code in src/alnoms/algorithms/math/simplex.py
primal()
Returns the optimal primal solution vector x.
Source code in src/alnoms/algorithms/math/simplex.py
π’ Fundamental Logic
Provides industrial-grade implementations of fundamental sorting algorithms. Includes elementary sorts (Selection, Insertion, Shell) and advanced sorts (Merge, Quick, Heap).
Features
- Generator Support: All functions support a 'visualize=True' flag to yield intermediate states for animation.
- Optimization: Quick Sort uses 3-way partitioning (Dijkstra) for duplicate handling.
- Efficiency: Merge Sort uses a single auxiliary array to reduce memory overhead.
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Chapter 2.
heap_sort(arr, visualize=False)
Heap Sort: Uses a binary heap to sort in-place. Guarantees O(N log N) time with O(1) space.
Source code in src/alnoms/algorithms/sorting.py
insertion_sort(arr, visualize=False)
Insertion Sort: Builds the sort by moving elements one at a time. Excellent for partially sorted arrays or small subarrays.
Complexity: Time O(N^2) (O(N) best case) | Space O(1)
Source code in src/alnoms/algorithms/sorting.py
merge_sort(arr, visualize=False)
Merge Sort: Recursive divide-and-conquer. Guarantees O(N log N) time, but requires O(N) auxiliary space.
Source code in src/alnoms/algorithms/sorting.py
quick_sort(arr, visualize=False)
Quick Sort (3-Way Partition): The standard for general purpose sorting. Uses Dijkstra's 3-way partitioning to handle duplicate keys efficiently.
Complexity: Time O(N log N) average | Space O(log N) recursion
Source code in src/alnoms/algorithms/sorting.py
selection_sort(arr, visualize=False)
Selection Sort: Scans for the minimum item and swaps it into place.
Complexity: Time O(N^2) | Space O(1)
Source code in src/alnoms/algorithms/sorting.py
shell_sort(arr, visualize=False)
Shell Sort: An optimized Insertion Sort using 'h-gaps'. Moves elements long distances to produce a partially sorted array, then finishes with standard insertion sort.
Complexity: Time O(N^1.5) approx | Space O(1)
Source code in src/alnoms/algorithms/sorting.py
Searching Algorithms.
This module provides efficient algorithms for searching in lists. It covers standard Binary Search for sorted arrays and the QuickSelect algorithm for finding the k-th smallest element in unsorted arrays.
Functions:
| Name | Description |
|---|---|
- binary_search |
Returns the index of a key in a sorted list. |
- rank |
Returns the number of elements strictly less than the key. |
- quick_select |
Finds the k-th smallest element in O(N) time (on average). |
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 1.1 and 2.3.
binary_search(a, key)
Searches for a key in a sorted list using Binary Search.
Time Complexity: O(log N) Space Complexity: O(1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
List[Any]
|
A sorted list of comparable elements. |
required |
key
|
Any
|
The element to search for. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The index of the key if found, otherwise -1. |
Source code in src/alnoms/algorithms/searching.py
quick_select(a, k)
Finds the k-th smallest element in an unsorted list.
This uses the partitioning logic from QuickSort to locate the element at index 'k' if the array were sorted. It does NOT fully sort the array.
Time Complexity: O(N) average, O(N^2) worst case (rare with shuffle). Space Complexity: O(1) (in-place).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
List[Any]
|
An unsorted list. |
required |
k
|
int
|
The rank to retrieve (0 = min, N-1 = max). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The k-th smallest element. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If k is out of bounds. |
Source code in src/alnoms/algorithms/searching.py
rank(a, key)
Returns the number of elements in the sorted list strictly less than key.
This is effectively a Binary Search that returns the insertion point. If the key exists, it returns the index of the first occurrence. If the key does not exist, it returns the index where it would be inserted.
Time Complexity: O(log N)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
List[Any]
|
A sorted list. |
required |
key
|
Any
|
The element to rank. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The rank of the key (0 to N). |
Source code in src/alnoms/algorithms/searching.py
String Processing Algorithms.
This module provides efficient algorithms for sorting strings, searching for substring patterns, and compressing data.
Features
- LSD Sort: Least-Significant-Digit radix sort (Stable, for fixed-length strings).
- MSD Sort: Most-Significant-Digit radix sort (General purpose string sort).
- KMP Search: Knuth-Morris-Pratt substring search (Linear time, no backup).
- Boyer-Moore: Substring search with character skipping (Sub-linear average time).
- Huffman: Prefix-free coding for lossless compression.
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Chapter 5.
BoyerMoore
Boyer-Moore Substring Search (Bad Character Rule).
Skips sections of text by analyzing the character that caused a mismatch.
Source code in src/alnoms/algorithms/strings.py
Huffman
Huffman Compression.
Constructs an optimal prefix-free code for a given string based on character frequency. Returns the binary string representation and the decoding tree.
Source code in src/alnoms/algorithms/strings.py
compress(s)
staticmethod
Compresses string s using Huffman coding.
Returns:
| Type | Description |
|---|---|
Tuple[str, Dict[str, str]]
|
Tuple[str, Dict]: (Binary String, Code Map) |
Source code in src/alnoms/algorithms/strings.py
KMP
Knuth-Morris-Pratt Substring Search.
Precomputes a Deterministic Finite Automaton (DFA) from the pattern to allow searching without backing up the text pointer.
Source code in src/alnoms/algorithms/strings.py
search(txt)
Searches for the pattern in the given text.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The index of the first occurrence, or -1 if not found. |
Source code in src/alnoms/algorithms/strings.py
LZW
Lempel-Ziv-Welch (LZW) Compression.
A dictionary-based compression algorithm that is particularly effective for data with repeated patterns. It builds a dictionary of substrings encountered in the data and represents them with shorter codes.
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 5.5.
Source code in src/alnoms/algorithms/strings.py
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 | |
compress(s)
staticmethod
Compresses a string into a list of dictionary indices.
Time Complexity: O(N) where N is the length of the string. Space Complexity: O(K) where K is the number of unique substrings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
s
|
str
|
The input string to compress. |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
List[int]: A list of integer codes representing the compressed data. |
Source code in src/alnoms/algorithms/strings.py
decompress(compressed)
staticmethod
Decompresses a list of LZW codes back into the original string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compressed
|
List[int]
|
The list of integer codes to decompress. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The original uncompressed string. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an invalid or corrupted code is encountered. |
Source code in src/alnoms/algorithms/strings.py
lsd_sort(a, w)
Sorts an array of fixed-length strings using Least-Significant-Digit Radix Sort.
Time Complexity: O(W * N) where W is width, N is number of strings. Space Complexity: O(N + R) where R is alphabet size. Stability: Stable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
List[str]
|
List of strings, all of length w. |
required |
w
|
int
|
The fixed length of the strings. |
required |
Source code in src/alnoms/algorithms/strings.py
msd_sort(a)
Sorts an array of strings using Most-Significant-Digit Radix Sort.
Suitable for variable-length strings. Recursive implementation.
Time Complexity: O(N * W) worst case, much faster for random strings. Space Complexity: O(N + R) per recursion level. Stability: Stable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
List[str]
|
List of strings to sort. |
required |
Source code in src/alnoms/algorithms/strings.py
Contains two-pointer algorithms like Floyd's Cycle Detection (Tortoise & Hare).
find_cycle_start(head)
Locates the exact node where a cycle begins in a Singly Linked List.
Time Complexity: O(N) Space Complexity: O(1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
head
|
Node
|
The head node of the linked list. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Node |
Optional[Node]
|
The node where the cycle begins, or None if no cycle exists. |
Source code in src/alnoms/algorithms/pointers.py
has_cycle(head)
Detects if a Singly Linked List contains a cycle using Floyd's Tortoise and Hare algorithm.
Time Complexity: O(N) Space Complexity: O(1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
head
|
Node
|
The head node of the linked list. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if a cycle exists, False otherwise. |
Source code in src/alnoms/algorithms/pointers.py
π¦ Data Structures (alnoms.structures)
Low-latency, memory-efficient structures designed for high-scale environments.
π³ Non-Linear & Hierarchical
Binary Search Tree (BST) Implementation.
This module provides a recursive implementation of a symbol table (map) using a binary search tree. It supports efficient key-value lookups, insertions, and ordered operations.
Features
- Generic Key-Value storage (Keys must be comparable).
- Ordered iteration (In-order traversal).
- Hibbard Deletion for efficient removal.
- Rank and Select operations.
Time Complexity
- Average Case: O(log N) for search/insert/delete.
- Worst Case: O(N) if the tree becomes unbalanced (sorted input). (Use Red-Black BST to guarantee O(log N)).
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 3.2.
BinarySearchTree
A symbol table implemented using a Binary Search Tree. Keys are kept in sorted order.
Source code in src/alnoms/structures/trees.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | |
__init__()
contains(key)
delete(key)
Removes the key and its value from the table. This uses Hibbard Deletion.
delete_min()
floor(key)
Returns the largest key less than or equal to key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The target key. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Any]
|
The floor key, or None if no such key exists. |
Source code in src/alnoms/structures/trees.py
get(key)
Returns the value associated with the given key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The key to search for. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Any]
|
The value associated with the key, or None if not found. |
Source code in src/alnoms/structures/trees.py
is_empty()
keys()
max()
min()
put(key, val)
Inserts the key-value pair into the table. If the key already exists, updates the value. If the value is None, deletes the key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The key to insert. |
required |
val
|
Any
|
The value to associate. |
required |
Source code in src/alnoms/structures/trees.py
RedBlackBST
A Left-Leaning Red-Black BST. Guarantees O(log N) search and insert times even in worst case.
Source code in src/alnoms/structures/trees.py
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | |
get(key)
put(key, val)
Inserts key-value pair, maintaining perfect black balance.
Graph Data Structures.
This module provides the core container classes for graph algorithms: 1. Graph: Undirected graph using adjacency lists. 2. Digraph: Directed graph using adjacency lists. 3. EdgeWeightedGraph: Undirected graph where edges have weights. 4. Edge: Helper class representing a weighted connection.
Implementation Details
- Representation: Adjacency Lists (Space complexity O(V + E)).
- Performance:
- Add Edge: O(1)
- Iterate Adj: O(degree(v))
- Check Edge: O(degree(v))
- Self-loops and parallel edges are allowed by default.
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 4.1, 4.2, 4.3.
Digraph
Directed graph data structure (Digraph).
Edges are directed: add_edge(v, w) means v -> w ONLY.
Source code in src/alnoms/structures/graphs.py
E()
V()
__init__(V)
Initializes an empty digraph with V vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
V
|
int
|
Number of vertices. |
required |
Source code in src/alnoms/structures/graphs.py
add_edge(v, w)
Adds a directed edge from v to w.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
Source vertex. |
required |
w
|
int
|
Destination vertex. |
required |
Source code in src/alnoms/structures/graphs.py
adj(v)
in_degree(v)
out_degree(v)
reverse()
Returns a new Digraph with all edges reversed. Useful for finding Strongly Connected Components (Kosaraju-Sharir).
Source code in src/alnoms/structures/graphs.py
Edge
Weighted edge abstraction. Represents a connection between two vertices with a weight. Implements comparison operators for sorting (needed for Kruskal's MST).
Source code in src/alnoms/structures/graphs.py
either()
other(vertex)
Returns the other endpoint of this edge given one vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex
|
int
|
One of the endpoints. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If vertex is not one of the endpoints. |
Source code in src/alnoms/structures/graphs.py
EdgeWeightedGraph
Undirected graph where edges have weights. Used for Minimum Spanning Trees (MST) and Shortest Path algorithms.
Source code in src/alnoms/structures/graphs.py
__init__(V)
Initializes empty weighted graph.
add_edge(e)
Adds a weighted edge to the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
e
|
Edge
|
The edge object to add. |
required |
Source code in src/alnoms/structures/graphs.py
adj(v)
edges()
Returns all edges in the graph.
Source code in src/alnoms/structures/graphs.py
FlowEdge
Capacitated edge with flow. Used for Max-Flow / Min-Cut algorithms.
Source code in src/alnoms/structures/graphs.py
__init__(v, w, capacity)
Initializes a flow edge from v to w with given capacity.
Source code in src/alnoms/structures/graphs.py
add_residual_flow_to(vertex, delta)
Adds residual flow toward the given vertex.
Source code in src/alnoms/structures/graphs.py
from_v()
other(vertex)
Returns the endpoint other than the given vertex.
residual_capacity_to(vertex)
Returns the residual capacity toward the given vertex.
Source code in src/alnoms/structures/graphs.py
FlowNetwork
Network of capacitated flow edges.
Source code in src/alnoms/structures/graphs.py
Graph
Undirected graph data structure.
Implemented using an array of lists. Each index 'v' contains a list of vertices adjacent to 'v'.
Source code in src/alnoms/structures/graphs.py
E()
V()
__init__(V)
Initializes an empty graph with V vertices and 0 edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
V
|
int
|
Number of vertices. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If V is negative. |
Source code in src/alnoms/structures/graphs.py
add_edge(v, w)
Adds an undirected edge between vertices v and w.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
First vertex. |
required |
w
|
int
|
Second vertex. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If v or w are out of bounds. |
Source code in src/alnoms/structures/graphs.py
adj(v)
Returns an iterator over the vertices adjacent to vertex v.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex. |
required |
Returns:
| Type | Description |
|---|---|
Iterable[int]
|
Iterable[int]: Neighbors of v. |
Source code in src/alnoms/structures/graphs.py
String Symbol Tables (Tries).
This module provides specialized symbol table implementations where keys are strings. Unlike generic hash tables or BSTs, these structures use the characters of the key to guide the search, allowing for advanced operations like prefix matching.
Classes:
| Name | Description |
|---|---|
1. TrieST |
R-way Trie (Fastest search, high memory usage). |
2. TST |
Ternary Search Trie (Balanced memory and speed, supports Unicode well). |
Features
- O(L) search time where L is string length (independent of N keys).
- Prefix matching (keys_with_prefix).
- Longest prefix matching.
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 5.2.
TST
Ternary Search Trie (TST).
A specialized trie where each node has 3 children (left, mid, right). More memory efficient than R-way tries for large alphabets (like Unicode).
Source code in src/alnoms/structures/tries.py
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | |
get(key)
Returns value associated with key.
keys()
keys_with_prefix(prefix)
Returns keys starting with prefix.
Source code in src/alnoms/structures/tries.py
put(key, val)
Inserts key-value pair.
Source code in src/alnoms/structures/tries.py
TrieST
R-way Trie Symbol Table.
Uses an array of R links at every node. Fast access but consumes significant memory if keys are sparse or the alphabet is large. Default R=256 (Extended ASCII).
Source code in src/alnoms/structures/tries.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
__init__(r=256)
Initializes an empty R-way Trie.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r
|
int
|
Alphabet size. Default 256 (Extended ASCII). |
256
|
delete(key)
get(key)
Returns the value associated with the given string key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The search key. |
required |
keys()
keys_with_prefix(prefix)
Returns all keys that start with the given prefix.
put(key, val)
π Specialized Structures
This module provides fundamental linear data structures optimized for performance. It includes node-based implementations of Lists, Stacks, Queues, and Bags to ensure O(1) time complexity for core operations, avoiding the overhead of dynamic array resizing found in standard Python lists.
Classes:
| Name | Description |
|---|---|
1. SinglyLinkedList |
Basic node-based list (Forward traversal). |
2. DoublyLinkedList |
Bidirectional node-based list. |
3. Stack |
LIFO (Last-In First-Out) structure. |
4. Queue |
FIFO (First-In First-Out) structure. |
5. Bag |
Unordered collection for collecting items. |
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 1.3.
Bag
Bases: Generic[T]
A collection where removing items is not supported. Its purpose is to provide the ability to collect items and then iterate over them.
Time Complexity
Source code in src/alnoms/structures/linear.py
__init__()
__iter__()
Iterates over the items in the bag (order is LIFO but irrelevant).
add(item)
Adds an item to the bag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
The item to add. |
required |
is_empty()
DoublyLinkedList
An advanced Doubly Linked List. Supports bidirectional traversal and O(1) tail operations.
Source code in src/alnoms/structures/linear.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | |
__init__()
__iter__()
__len__()
append(data)
Appends a node to the end of the list.
Time Complexity: O(1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The data to append. |
required |
Source code in src/alnoms/structures/linear.py
display_forward()
is_empty()
prepend(data)
Inserts a node at the beginning of the list.
Time Complexity: O(1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The data to prepend. |
required |
Source code in src/alnoms/structures/linear.py
remove(data)
Removes the first occurrence of a specific value.
Time Complexity: O(N)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The value to remove. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if removed, False otherwise. |
Source code in src/alnoms/structures/linear.py
DoublyNode
A node for Doubly Linked structures.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
Any
|
The value stored in the node. |
next |
Optional[DoublyNode]
|
Reference to the next node. |
prev |
Optional[DoublyNode]
|
Reference to the previous node. |
Source code in src/alnoms/structures/linear.py
Node
A standard node for Singly Linked structures.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
Any
|
The value stored in the node. |
next |
Optional[Node]
|
Reference to the next node in the sequence. |
Source code in src/alnoms/structures/linear.py
Queue
Bases: Generic[T]
A FIFO (First-In First-Out) queue. Maintains pointers to both head (first) and tail (last) to ensure O(1) enqueue and dequeue operations.
Source code in src/alnoms/structures/linear.py
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 | |
__init__()
__iter__()
dequeue()
Removes and returns the item least recently added to the queue.
Time Complexity: O(1)
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The item from the front of the queue. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the queue is empty. |
Source code in src/alnoms/structures/linear.py
enqueue(item)
Adds an item to the end of the queue.
Time Complexity: O(1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
The item to add. |
required |
Source code in src/alnoms/structures/linear.py
is_empty()
peek()
Returns the item at the front of the queue without removing it.
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The item at the front. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the queue is empty. |
Source code in src/alnoms/structures/linear.py
SinglyLinkedList
A foundational Singly Linked List. Optimized for fast O(1) insertions at the head and linear traversals.
Source code in src/alnoms/structures/linear.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |
__init__()
__iter__()
Iterates through the list data from head to tail.
Yields:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The data stored in each node. |
__len__()
append(data)
Appends a node to the very end of the list.
Time Complexity: O(N)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The data to append. |
required |
Source code in src/alnoms/structures/linear.py
display()
Returns a string representation of the list for debugging.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Format '1 -> 2 -> NULL'. |
Source code in src/alnoms/structures/linear.py
insert_at_head(data)
Inserts a new node at the beginning of the list.
Time Complexity: O(1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The data to store. |
required |
Source code in src/alnoms/structures/linear.py
is_empty()
remove(data)
Removes the first occurrence of a specific value from the list.
Time Complexity: O(N)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The value to remove. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if removed, False otherwise. |
Source code in src/alnoms/structures/linear.py
Stack
Bases: Generic[T]
A LIFO (Last-In First-Out) stack. Implemented using a linked list to ensure O(1) worst-case time for push/pop, avoiding the resizing overhead of array-based stacks.
Source code in src/alnoms/structures/linear.py
__init__()
__iter__()
is_empty()
peek()
Returns the item at the top of the stack without removing it.
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The item at the top. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the stack is empty. |
Source code in src/alnoms/structures/linear.py
pop()
Removes and returns the item most recently added to the stack.
Time Complexity: O(1)
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The item from the top of the stack. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the stack is empty. |
Source code in src/alnoms/structures/linear.py
push(item)
Adds an item to the top of the stack.
Time Complexity: O(1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
The item to push. |
required |
Source code in src/alnoms/structures/linear.py
Hash Table Implementations.
This module provides two standard hash table implementations for key-value storage: 1. SeparateChainingHashST: Uses a list of buckets to handle collisions. 2. LinearProbingHashST: Uses open addressing (probing) to handle collisions.
Features
- Generic Key-Value storage (Keys must be hashable).
- Dynamic resizing (LinearProbing) to maintain O(1) average performance.
- Efficient lookups, insertions, and deletions.
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 3.4.
LinearProbingHashST
Symbol table implementation using a hash table with linear probing.
Uses two parallel arrays for keys and values. Maintains a load factor between 1/8 and 1/2 by dynamic resizing.
Source code in src/alnoms/structures/hashtable.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | |
__init__(capacity=16)
Initializes the linear probing hash table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
capacity
|
int
|
Initial capacity of the table. |
16
|
Source code in src/alnoms/structures/hashtable.py
contains(key)
delete(key)
Removes the key and its associated value.
This method employs 'Cluster Re-hashing': when a key is deleted, all subsequent keys in the same cluster are removed and re-inserted to maintain the integrity of the probe sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The key to remove. |
required |
Source code in src/alnoms/structures/hashtable.py
get(key)
Returns the value associated with the key.
Follows the probe sequence to find the key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The key to search for. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Any]
|
The value if found, otherwise None. |
Source code in src/alnoms/structures/hashtable.py
is_empty()
keys()
Returns all keys in the table.
Returns:
| Type | Description |
|---|---|
List[Any]
|
List[Any]: A list of all keys currently in the table. |
put(key, val)
Inserts the key-value pair into the table.
Handles collisions using linear probing. Automatically resizes the table if the load factor exceeds 1/2. If val is None, the key is deleted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The key to insert. |
required |
val
|
Any
|
The value to associate with the key. |
required |
Source code in src/alnoms/structures/hashtable.py
SeparateChainingHashST
Symbol table implementation using a hash table with separate chaining.
Each bucket contains a simple list of (key, value) tuples. If M is the number of buckets, average search time is O(N/M).
Source code in src/alnoms/structures/hashtable.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
__init__(m=997)
Initializes the hash table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
m
|
int
|
Number of chains (buckets). Defaults to a prime number. |
997
|
Source code in src/alnoms/structures/hashtable.py
contains(key)
delete(key)
Removes the key and its associated value from the table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The key to remove. |
required |
Source code in src/alnoms/structures/hashtable.py
get(key)
Returns the value associated with the key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The key to search for. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Any]
|
The value if found, otherwise None. |
Source code in src/alnoms/structures/hashtable.py
is_empty()
keys()
Returns all keys in the table.
Returns:
| Type | Description |
|---|---|
List[Any]
|
List[Any]: A list of all keys currently in the table. |
Source code in src/alnoms/structures/hashtable.py
put(key, val)
Inserts the key-value pair into the table.
Updates the value if the key already exists. If the value is None, the key is removed from the table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The key to insert. |
required |
val
|
Any
|
The value to associate with the key. |
required |
Source code in src/alnoms/structures/hashtable.py
Geometric Data Structures.
This module provides spatial partitioning structures for efficient geometric searching, including Kd-Trees (2d-Trees) and Quadtrees.
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 3.6 / Chapter 6.
KdTree
A 2d-Tree implementation for 2D points.
Uses alternating axis-aligned partitioning (vertical/horizontal) to organize points in 2D space.
Source code in src/alnoms/structures/geometric.py
__init__()
contains(point)
insert(point)
Inserts a point into the 2d-Tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
point
|
Tuple[float, float]
|
The (x, y) coordinates to insert. |
required |
Quadtree
A Quadtree for 2D spatial partitioning.
Partitions space into four quadrants (NW, NE, SW, SE).
Source code in src/alnoms/structures/geometric.py
__init__(x_min, y_min, x_max, y_max)
Initializes a Quadtree within a specific bounding box.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x_min, y_min
|
Lower bounds of the area. |
required | |
x_max, y_max
|
Upper bounds of the area. |
required |
Source code in src/alnoms/structures/geometric.py
insert(x, y, value)
Disjoint Set (Union-Find) Data Structure.
This module implements the Disjoint Set data structure, also known as Union-Find. It models a collection of disjoint sets, supporting efficient 'union' (merge) and 'find' (lookup) operations.
Implementation Details
- Algorithm: Weighted Quick-Union with Path Compression.
- Time Complexity: O(alpha(N)) for both union and find, where alpha is the inverse Ackermann function. In practice, this is nearly constant time.
- Space Complexity: O(N) linear space.
Reference
Algorithms, 4th Edition by Sedgewick and Wayne, Section 1.5.
DisjointSet
A data structure to manage a set of elements partitioned into disjoint subsets.
This implementation uses 'weighted quick-union by size' to minimize tree height and 'path compression' to flatten the tree during find operations.
Source code in src/alnoms/structures/disjoint.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
count
property
Returns the number of disjoint sets (connected components).
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of components. |
__init__(n)
Initializes an empty disjoint set structure with n elements (0 to n-1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
The number of elements. Must be non-negative. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If n is negative. |
Source code in src/alnoms/structures/disjoint.py
connected(p, q)
Determines whether elements p and q are in the same set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
int
|
First element. |
required |
q
|
int
|
Second element. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if p and q are connected, False otherwise. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If p or q are invalid indices. |
Source code in src/alnoms/structures/disjoint.py
find(p)
Returns the canonical element (root) of the set containing element p.
This method employs path compression: after finding the root, it links every visited node directly to the root, flattening the structure for future operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
int
|
The element to look up. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The canonical root identifier of the component. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If p is not a valid index (0 <= p < n). |
Source code in src/alnoms/structures/disjoint.py
union(p, q)
Merges the set containing element p with the set containing element q.
If p and q are already in the same set, this method returns immediately. Otherwise, it merges the smaller tree into the larger tree (weighted union).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
int
|
First element. |
required |
q
|
int
|
Second element. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If p or q are invalid indices. |
Source code in src/alnoms/structures/disjoint.py
π Infrastructure & Utils (alnoms.utils)
Governance tools and deterministic data generation for laboratory environments.
β±οΈ Performance Profiling
Provides precision timing and algorithmic complexity analysis for research.
Profiler
Industrial-grade performance analyzer for Arprax Lab.
Provides precision timing, statistical analysis, and doubling-test complexity estimation. Designed to work without external dependencies.
Attributes:
| Name | Type | Description |
|---|---|---|
repeats |
int
|
Number of times to run each benchmark. |
warmup |
int
|
Number of discarded runs to prime the CPU cache. |
mode |
str
|
Statistical mode for final result ('min', 'mean', 'median'). |
Source code in src/alnoms/utils/profiler.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
__init__(repeats=5, warmup=1, mode='min')
Initializes the Profiler with user-defined benchmark settings.
Source code in src/alnoms/utils/profiler.py
benchmark(func, *args)
Runs a function with garbage collection disabled to ensure timing purity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
The function to measure. |
required |
*args
|
Any
|
Arguments to pass to the function. |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The measured time in seconds based on the 'mode' setting. |
Source code in src/alnoms/utils/profiler.py
print_analysis(func_name, results)
Prints a formatted results table from a doubling test.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func_name
|
str
|
Name of the analyzed algorithm. |
required |
results
|
List[Dict]
|
Data from run_doubling_test. |
required |
Source code in src/alnoms/utils/profiler.py
print_decorator_report()
Prints a summary table of all tracked functions and stopwatch blocks.
Source code in src/alnoms/utils/profiler.py
profile(func)
Decorator to track function execution time during normal program flow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
The function to be decorated. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable
|
The wrapped function. |
Source code in src/alnoms/utils/profiler.py
run_doubling_test(func, input_gen, start_n=250, rounds=6)
Performs doubling analysis to estimate Big O complexity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
Algorithm to analyze. |
required |
input_gen
|
Callable
|
Function that generates data for size N. |
required |
start_n
|
int
|
Initial input size. |
250
|
rounds
|
int
|
How many times to double N. |
6
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: A log of N, Time, Ratio, and estimated Complexity. |
Source code in src/alnoms/utils/profiler.py
run_stress_suite(funcs, input_gen, n_values=[1000, 2000, 4000])
Runs multiple algorithms against multiple input sizes for head-to-head comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
funcs
|
Dict
|
Map of {'Name': Function}. |
required |
input_gen
|
Callable
|
Data generator function. |
required |
n_values
|
List[int]
|
List of N sizes to test. |
[1000, 2000, 4000]
|
Returns:
| Type | Description |
|---|---|
Dict[int, Dict[str, float]]
|
Dict[int, Dict[str, float]]: Nested mapping of {N: {Name: Time}}. |
Source code in src/alnoms/utils/profiler.py
stopwatch(label='Block')
Context manager for precision timing of a specific code block.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Name of the block for the final report. |
'Block'
|
Source code in src/alnoms/utils/profiler.py
π² Generators & I/O
Provides industrial-grade tools for creating research-ready datasets.
large_scale_dataset(n)
High-performance data generator for large-scale research.
Attempts to use NumPy for speed if available; otherwise, falls back to standard Python random generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
The number of elements to generate. |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
List[int]: A list of random integers. |
Source code in src/alnoms/utils/generators.py
random_array(n, lo=0, hi=1000)
Generates an array of n random integers using Python's built-in random module.
This serves as the default, dependency-free generator for the library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
The number of elements to generate. |
required |
lo
|
int
|
The lower bound of the random range (inclusive). |
0
|
hi
|
int
|
The upper bound of the random range (inclusive). |
1000
|
Returns:
| Type | Description |
|---|---|
List[int]
|
List[int]: A list of n random integers. |
Source code in src/alnoms/utils/generators.py
reverse_sorted_array(n)
Legacy wrapper for descending order.
Frequently used for 'Worst Case' algorithm testing in the Arprax Lab.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
The number of elements to generate. |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
List[int]: A list containing integers from n-1 down to 0. |
Source code in src/alnoms/utils/generators.py
sorted_array(n, reverse=False)
Generates an array of n integers in sorted order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
The number of elements to generate. |
required |
reverse
|
bool
|
If True, returns descending order (Worst Case). |
False
|
Returns:
| Type | Description |
|---|---|
List[int]
|
List[int]: A list containing integers from 0 to n-1 (or reversed). |
Source code in src/alnoms/utils/generators.py
Input/Output Utilities for Test Data.
This module provides utility functions to load large test datasets from files. It is designed to handle common formats used in algorithm testing, such as whitespace-separated integers (for sorting) or strings (for tries/searching).
Functions:
| Name | Description |
|---|---|
- read_all_ints |
Reads all integers from a file (whitespace-separated). |
- read_all_strings |
Reads all string tokens from a file (whitespace-separated). |
- read_lines |
Reads all lines from a file, stripping whitespace. |
Usage
from alnoms.algos.utils.io import read_all_ints data = read_all_ints("tests/data/1Kints.txt")
read_all_ints(path)
Reads all integers from the specified file.
The file is expected to contain integers separated by any amount of whitespace (spaces, tabs, newlines). This is the standard format for sorting and searching benchmarks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The absolute or relative path to the file. |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
List[int]: A list of all integers found in the file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file path does not exist. |
ValueError
|
If the file contains tokens that cannot be parsed as integers. |
Source code in src/alnoms/utils/io.py
read_all_strings(path)
Reads all whitespace-separated strings from the specified file.
Useful for loading data for Trie tests or String Sorts (MSD/LSD).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The absolute or relative path to the file. |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: A list of all string tokens found in the file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file path does not exist. |
Source code in src/alnoms/utils/io.py
read_lines(path)
Reads all lines from the file, stripping leading and trailing whitespace.
Preserves empty lines as empty strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The absolute or relative path to the file. |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: A list of lines. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file path does not exist. |