Skip to content

Commit 9e7ea93

Browse files
committed
2 parents 9e68fb7 + fcf82a1 commit 9e7ea93

File tree

7 files changed

+345
-29
lines changed

7 files changed

+345
-29
lines changed

Diff for: CONTRIBUTING.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ We want your work to be readable by others; therefore, we encourage you to note
9696

9797
```bash
9898
python3 -m pip install ruff # only required the first time
99-
ruff .
99+
ruff check
100100
```
101101

102102
- Original code submission require docstrings or comments to describe your work.

Diff for: data_structures/stacks/lexicographical_numbers.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from collections.abc import Iterator
2+
3+
4+
def lexical_order(max_number: int) -> Iterator[int]:
5+
"""
6+
Generate numbers in lexical order from 1 to max_number.
7+
8+
>>> " ".join(map(str, lexical_order(13)))
9+
'1 10 11 12 13 2 3 4 5 6 7 8 9'
10+
>>> list(lexical_order(1))
11+
[1]
12+
>>> " ".join(map(str, lexical_order(20)))
13+
'1 10 11 12 13 14 15 16 17 18 19 2 20 3 4 5 6 7 8 9'
14+
>>> " ".join(map(str, lexical_order(25)))
15+
'1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 23 24 25 3 4 5 6 7 8 9'
16+
>>> list(lexical_order(12))
17+
[1, 10, 11, 12, 2, 3, 4, 5, 6, 7, 8, 9]
18+
"""
19+
20+
stack = [1]
21+
22+
while stack:
23+
num = stack.pop()
24+
if num > max_number:
25+
continue
26+
27+
yield num
28+
if (num % 10) != 9:
29+
stack.append(num + 1)
30+
31+
stack.append(num * 10)
32+
33+
34+
if __name__ == "__main__":
35+
from doctest import testmod
36+
37+
testmod()
38+
print(f"Numbers from 1 to 25 in lexical order: {list(lexical_order(26))}")

Diff for: dynamic_programming/longest_common_subsequence.py

+18
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,24 @@ def longest_common_subsequence(x: str, y: str):
2828
(2, 'ph')
2929
>>> longest_common_subsequence("computer", "food")
3030
(1, 'o')
31+
>>> longest_common_subsequence("", "abc") # One string is empty
32+
(0, '')
33+
>>> longest_common_subsequence("abc", "") # Other string is empty
34+
(0, '')
35+
>>> longest_common_subsequence("", "") # Both strings are empty
36+
(0, '')
37+
>>> longest_common_subsequence("abc", "def") # No common subsequence
38+
(0, '')
39+
>>> longest_common_subsequence("abc", "abc") # Identical strings
40+
(3, 'abc')
41+
>>> longest_common_subsequence("a", "a") # Single character match
42+
(1, 'a')
43+
>>> longest_common_subsequence("a", "b") # Single character no match
44+
(0, '')
45+
>>> longest_common_subsequence("abcdef", "ace") # Interleaved subsequence
46+
(3, 'ace')
47+
>>> longest_common_subsequence("ABCD", "ACBD") # No repeated characters
48+
(3, 'ABD')
3149
"""
3250
# find the length of strings
3351

Diff for: graphs/kahns_algorithm_topo.py

+46-21
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,61 @@
1-
def topological_sort(graph):
1+
def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:
22
"""
3-
Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph
4-
using BFS
3+
Perform topological sorting of a Directed Acyclic Graph (DAG)
4+
using Kahn's Algorithm via Breadth-First Search (BFS).
5+
6+
Topological sorting is a linear ordering of vertices in a graph such that for
7+
every directed edge u → v, vertex u comes before vertex v in the ordering.
8+
9+
Parameters:
10+
graph: Adjacency list representing the directed graph where keys are
11+
vertices, and values are lists of adjacent vertices.
12+
13+
Returns:
14+
The topologically sorted order of vertices if the graph is a DAG.
15+
Returns None if the graph contains a cycle.
16+
17+
Example:
18+
>>> graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
19+
>>> topological_sort(graph)
20+
[0, 1, 2, 3, 4, 5]
21+
22+
>>> graph_with_cycle = {0: [1], 1: [2], 2: [0]}
23+
>>> topological_sort(graph_with_cycle)
524
"""
25+
626
indegree = [0] * len(graph)
727
queue = []
8-
topo = []
9-
cnt = 0
28+
topo_order = []
29+
processed_vertices_count = 0
1030

31+
# Calculate the indegree of each vertex
1132
for values in graph.values():
1233
for i in values:
1334
indegree[i] += 1
1435

36+
# Add all vertices with 0 indegree to the queue
1537
for i in range(len(indegree)):
1638
if indegree[i] == 0:
1739
queue.append(i)
1840

41+
# Perform BFS
1942
while queue:
2043
vertex = queue.pop(0)
21-
cnt += 1
22-
topo.append(vertex)
23-
for x in graph[vertex]:
24-
indegree[x] -= 1
25-
if indegree[x] == 0:
26-
queue.append(x)
27-
28-
if cnt != len(graph):
29-
print("Cycle exists")
30-
else:
31-
print(topo)
32-
33-
34-
# Adjacency List of Graph
35-
graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
36-
topological_sort(graph)
44+
processed_vertices_count += 1
45+
topo_order.append(vertex)
46+
47+
# Traverse neighbors
48+
for neighbor in graph[vertex]:
49+
indegree[neighbor] -= 1
50+
if indegree[neighbor] == 0:
51+
queue.append(neighbor)
52+
53+
if processed_vertices_count != len(graph):
54+
return None # no topological ordering exists due to cycle
55+
return topo_order # valid topological ordering
56+
57+
58+
if __name__ == "__main__":
59+
import doctest
60+
61+
doctest.testmod()

Diff for: maths/fibonacci.py

+88
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
88
NOTE 2: the Binet's formula function is much more limited in the size of inputs
99
that it can handle due to the size limitations of Python floats
10+
NOTE 3: the matrix function is the fastest and most memory efficient for large n
11+
1012
1113
See benchmark numbers in __main__ for performance comparisons/
1214
https://en.wikipedia.org/wiki/Fibonacci_number for more information
@@ -17,6 +19,9 @@
1719
from math import sqrt
1820
from time import time
1921

22+
import numpy as np
23+
from numpy import ndarray
24+
2025

2126
def time_func(func, *args, **kwargs):
2227
"""
@@ -230,6 +235,88 @@ def fib_binet(n: int) -> list[int]:
230235
return [round(phi**i / sqrt_5) for i in range(n + 1)]
231236

232237

238+
def matrix_pow_np(m: ndarray, power: int) -> ndarray:
239+
"""
240+
Raises a matrix to the power of 'power' using binary exponentiation.
241+
242+
Args:
243+
m: Matrix as a numpy array.
244+
power: The power to which the matrix is to be raised.
245+
246+
Returns:
247+
The matrix raised to the power.
248+
249+
Raises:
250+
ValueError: If power is negative.
251+
252+
>>> m = np.array([[1, 1], [1, 0]], dtype=int)
253+
>>> matrix_pow_np(m, 0) # Identity matrix when raised to the power of 0
254+
array([[1, 0],
255+
[0, 1]])
256+
257+
>>> matrix_pow_np(m, 1) # Same matrix when raised to the power of 1
258+
array([[1, 1],
259+
[1, 0]])
260+
261+
>>> matrix_pow_np(m, 5)
262+
array([[8, 5],
263+
[5, 3]])
264+
265+
>>> matrix_pow_np(m, -1)
266+
Traceback (most recent call last):
267+
...
268+
ValueError: power is negative
269+
"""
270+
result = np.array([[1, 0], [0, 1]], dtype=int) # Identity Matrix
271+
base = m
272+
if power < 0: # Negative power is not allowed
273+
raise ValueError("power is negative")
274+
while power:
275+
if power % 2 == 1:
276+
result = np.dot(result, base)
277+
base = np.dot(base, base)
278+
power //= 2
279+
return result
280+
281+
282+
def fib_matrix_np(n: int) -> int:
283+
"""
284+
Calculates the n-th Fibonacci number using matrix exponentiation.
285+
https://www.nayuki.io/page/fast-fibonacci-algorithms#:~:text=
286+
Summary:%20The%20two%20fast%20Fibonacci%20algorithms%20are%20matrix
287+
288+
Args:
289+
n: Fibonacci sequence index
290+
291+
Returns:
292+
The n-th Fibonacci number.
293+
294+
Raises:
295+
ValueError: If n is negative.
296+
297+
>>> fib_matrix_np(0)
298+
0
299+
>>> fib_matrix_np(1)
300+
1
301+
>>> fib_matrix_np(5)
302+
5
303+
>>> fib_matrix_np(10)
304+
55
305+
>>> fib_matrix_np(-1)
306+
Traceback (most recent call last):
307+
...
308+
ValueError: n is negative
309+
"""
310+
if n < 0:
311+
raise ValueError("n is negative")
312+
if n == 0:
313+
return 0
314+
315+
m = np.array([[1, 1], [1, 0]], dtype=int)
316+
result = matrix_pow_np(m, n - 1)
317+
return int(result[0, 0])
318+
319+
233320
if __name__ == "__main__":
234321
from doctest import testmod
235322

@@ -242,3 +329,4 @@ def fib_binet(n: int) -> list[int]:
242329
time_func(fib_memoization, num) # 0.0100 ms
243330
time_func(fib_recursive_cached, num) # 0.0153 ms
244331
time_func(fib_recursive, num) # 257.0910 ms
332+
time_func(fib_matrix_np, num) # 0.0000 ms

Diff for: searches/exponential_search.py

+113
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
#!/usr/bin/env python3
2+
3+
"""
4+
Pure Python implementation of exponential search algorithm
5+
6+
For more information, see the Wikipedia page:
7+
https://en.wikipedia.org/wiki/Exponential_search
8+
9+
For doctests run the following command:
10+
python3 -m doctest -v exponential_search.py
11+
12+
For manual testing run:
13+
python3 exponential_search.py
14+
"""
15+
16+
from __future__ import annotations
17+
18+
19+
def binary_search_by_recursion(
20+
sorted_collection: list[int], item: int, left: int = 0, right: int = -1
21+
) -> int:
22+
"""Pure implementation of binary search algorithm in Python using recursion
23+
24+
Be careful: the collection must be ascending sorted otherwise, the result will be
25+
unpredictable.
26+
27+
:param sorted_collection: some ascending sorted collection with comparable items
28+
:param item: item value to search
29+
:param left: starting index for the search
30+
:param right: ending index for the search
31+
:return: index of the found item or -1 if the item is not found
32+
33+
Examples:
34+
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 0, 0, 4)
35+
0
36+
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 15, 0, 4)
37+
4
38+
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 5, 0, 4)
39+
1
40+
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 6, 0, 4)
41+
-1
42+
"""
43+
if right < 0:
44+
right = len(sorted_collection) - 1
45+
if list(sorted_collection) != sorted(sorted_collection):
46+
raise ValueError("sorted_collection must be sorted in ascending order")
47+
if right < left:
48+
return -1
49+
50+
midpoint = left + (right - left) // 2
51+
52+
if sorted_collection[midpoint] == item:
53+
return midpoint
54+
elif sorted_collection[midpoint] > item:
55+
return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1)
56+
else:
57+
return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right)
58+
59+
60+
def exponential_search(sorted_collection: list[int], item: int) -> int:
61+
"""
62+
Pure implementation of an exponential search algorithm in Python.
63+
For more information, refer to:
64+
https://en.wikipedia.org/wiki/Exponential_search
65+
66+
Be careful: the collection must be ascending sorted, otherwise the result will be
67+
unpredictable.
68+
69+
:param sorted_collection: some ascending sorted collection with comparable items
70+
:param item: item value to search
71+
:return: index of the found item or -1 if the item is not found
72+
73+
The time complexity of this algorithm is O(log i) where i is the index of the item.
74+
75+
Examples:
76+
>>> exponential_search([0, 5, 7, 10, 15], 0)
77+
0
78+
>>> exponential_search([0, 5, 7, 10, 15], 15)
79+
4
80+
>>> exponential_search([0, 5, 7, 10, 15], 5)
81+
1
82+
>>> exponential_search([0, 5, 7, 10, 15], 6)
83+
-1
84+
"""
85+
if list(sorted_collection) != sorted(sorted_collection):
86+
raise ValueError("sorted_collection must be sorted in ascending order")
87+
88+
if sorted_collection[0] == item:
89+
return 0
90+
91+
bound = 1
92+
while bound < len(sorted_collection) and sorted_collection[bound] < item:
93+
bound *= 2
94+
95+
left = bound // 2
96+
right = min(bound, len(sorted_collection) - 1)
97+
return binary_search_by_recursion(sorted_collection, item, left, right)
98+
99+
100+
if __name__ == "__main__":
101+
import doctest
102+
103+
doctest.testmod()
104+
105+
# Manual testing
106+
user_input = input("Enter numbers separated by commas: ").strip()
107+
collection = sorted(int(item) for item in user_input.split(","))
108+
target = int(input("Enter a number to search for: "))
109+
result = exponential_search(sorted_collection=collection, item=target)
110+
if result == -1:
111+
print(f"{target} was not found in {collection}.")
112+
else:
113+
print(f"{target} was found at index {result} in {collection}.")

0 commit comments

Comments
 (0)