Skip to content
Open
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
22 changes: 16 additions & 6 deletions graphs/kahns_algorithm_topo.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from collections import deque


def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:
"""
Perform topological sorting of a Directed Acyclic Graph (DAG)
Expand All @@ -21,10 +24,17 @@ def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:

>>> graph_with_cycle = {0: [1], 1: [2], 2: [0]}
>>> topological_sort(graph_with_cycle)

>>> sparse_graph = {10: [20], 20: []}
>>> topological_sort(sparse_graph)
[10, 20]

>>> sparse_cycle = {10: [20], 20: [10]}
>>> topological_sort(sparse_cycle)
"""

indegree = [0] * len(graph)
queue = []
indegree = dict.fromkeys(graph, 0)
queue: deque[int] = deque()
topo_order = []
processed_vertices_count = 0

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

# Add all vertices with 0 indegree to the queue
for i in range(len(indegree)):
if indegree[i] == 0:
queue.append(i)
for vertex, count in indegree.items():
if count == 0:
queue.append(vertex)

# Perform BFS
while queue:
vertex = queue.pop(0)
vertex = queue.popleft()
processed_vertices_count += 1
topo_order.append(vertex)

Expand Down
6 changes: 2 additions & 4 deletions maths/matrix_exponentiation.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
"""Matrix Exponentiation"""

import timeit

"""
Matrix Exponentiation is a technique to solve linear recurrences in logarithmic time.
You read more about it here:
https://zobayer.blogspot.com/2010/11/matrix-exponentiation.html
https://www.hackerearth.com/practice/notes/matrix-exponentiation-1/
"""

import timeit


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