Skip to content

Commit 12ad81b

Browse files
Fix matrix exponentiation type annotations (#15076)
* fix: sub-interval midpoint formula in ternary search * fix(maths): resolve NameError on self-referential class type annotations in matrix_exponentiation.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix(maths): remove unnecessary future annotations import --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 35b7074 commit 12ad81b

2 files changed

Lines changed: 18 additions & 10 deletions

File tree

graphs/kahns_algorithm_topo.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
from collections import deque
2+
3+
14
def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:
25
"""
36
Perform topological sorting of a Directed Acyclic Graph (DAG)
@@ -21,10 +24,17 @@ def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:
2124
2225
>>> graph_with_cycle = {0: [1], 1: [2], 2: [0]}
2326
>>> topological_sort(graph_with_cycle)
27+
28+
>>> sparse_graph = {10: [20], 20: []}
29+
>>> topological_sort(sparse_graph)
30+
[10, 20]
31+
32+
>>> sparse_cycle = {10: [20], 20: [10]}
33+
>>> topological_sort(sparse_cycle)
2434
"""
2535

26-
indegree = [0] * len(graph)
27-
queue = []
36+
indegree = dict.fromkeys(graph, 0)
37+
queue: deque[int] = deque()
2838
topo_order = []
2939
processed_vertices_count = 0
3040

@@ -34,13 +44,13 @@ def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:
3444
indegree[i] += 1
3545

3646
# Add all vertices with 0 indegree to the queue
37-
for i in range(len(indegree)):
38-
if indegree[i] == 0:
39-
queue.append(i)
47+
for vertex, count in indegree.items():
48+
if count == 0:
49+
queue.append(vertex)
4050

4151
# Perform BFS
4252
while queue:
43-
vertex = queue.pop(0)
53+
vertex = queue.popleft()
4454
processed_vertices_count += 1
4555
topo_order.append(vertex)
4656

maths/matrix_exponentiation.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
1-
"""Matrix Exponentiation"""
2-
3-
import timeit
4-
51
"""
62
Matrix Exponentiation is a technique to solve linear recurrences in logarithmic time.
73
You read more about it here:
84
https://zobayer.blogspot.com/2010/11/matrix-exponentiation.html
95
https://www.hackerearth.com/practice/notes/matrix-exponentiation-1/
106
"""
117

8+
import timeit
9+
1210

1311
class Matrix:
1412
def __init__(self, arg: list[list] | int) -> None:

0 commit comments

Comments
 (0)