Skip to content

Commit 3f534f8

Browse files
authored
Merge branch 'TheAlgorithms:master' into longArthSub
2 parents 3f9bc29 + 59ff87d commit 3f534f8

File tree

2 files changed

+87
-28
lines changed

2 files changed

+87
-28
lines changed

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()

strings/min_cost_string_conversion.py

+41-7
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,27 @@ def compute_transform_tables(
1717
delete_cost: int,
1818
insert_cost: int,
1919
) -> tuple[list[list[int]], list[list[str]]]:
20+
"""
21+
Finds the most cost efficient sequence
22+
for converting one string into another.
23+
24+
>>> costs, operations = compute_transform_tables("cat", "cut", 1, 2, 3, 3)
25+
>>> costs[0][:4]
26+
[0, 3, 6, 9]
27+
>>> costs[2][:4]
28+
[6, 4, 3, 6]
29+
>>> operations[0][:4]
30+
['0', 'Ic', 'Iu', 'It']
31+
>>> operations[3][:4]
32+
['Dt', 'Dt', 'Rtu', 'Ct']
33+
34+
>>> compute_transform_tables("", "", 1, 2, 3, 3)
35+
([[0]], [['0']])
36+
"""
2037
source_seq = list(source_string)
2138
destination_seq = list(destination_string)
2239
len_source_seq = len(source_seq)
2340
len_destination_seq = len(destination_seq)
24-
2541
costs = [
2642
[0 for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1)
2743
]
@@ -31,33 +47,51 @@ def compute_transform_tables(
3147

3248
for i in range(1, len_source_seq + 1):
3349
costs[i][0] = i * delete_cost
34-
ops[i][0] = f"D{source_seq[i - 1]:c}"
50+
ops[i][0] = f"D{source_seq[i - 1]}"
3551

3652
for i in range(1, len_destination_seq + 1):
3753
costs[0][i] = i * insert_cost
38-
ops[0][i] = f"I{destination_seq[i - 1]:c}"
54+
ops[0][i] = f"I{destination_seq[i - 1]}"
3955

4056
for i in range(1, len_source_seq + 1):
4157
for j in range(1, len_destination_seq + 1):
4258
if source_seq[i - 1] == destination_seq[j - 1]:
4359
costs[i][j] = costs[i - 1][j - 1] + copy_cost
44-
ops[i][j] = f"C{source_seq[i - 1]:c}"
60+
ops[i][j] = f"C{source_seq[i - 1]}"
4561
else:
4662
costs[i][j] = costs[i - 1][j - 1] + replace_cost
47-
ops[i][j] = f"R{source_seq[i - 1]:c}" + str(destination_seq[j - 1])
63+
ops[i][j] = f"R{source_seq[i - 1]}" + str(destination_seq[j - 1])
4864

4965
if costs[i - 1][j] + delete_cost < costs[i][j]:
5066
costs[i][j] = costs[i - 1][j] + delete_cost
51-
ops[i][j] = f"D{source_seq[i - 1]:c}"
67+
ops[i][j] = f"D{source_seq[i - 1]}"
5268

5369
if costs[i][j - 1] + insert_cost < costs[i][j]:
5470
costs[i][j] = costs[i][j - 1] + insert_cost
55-
ops[i][j] = f"I{destination_seq[j - 1]:c}"
71+
ops[i][j] = f"I{destination_seq[j - 1]}"
5672

5773
return costs, ops
5874

5975

6076
def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]:
77+
"""
78+
Assembles the transformations based on the ops table.
79+
80+
>>> ops = [['0', 'Ic', 'Iu', 'It'],
81+
... ['Dc', 'Cc', 'Iu', 'It'],
82+
... ['Da', 'Da', 'Rau', 'Rat'],
83+
... ['Dt', 'Dt', 'Rtu', 'Ct']]
84+
>>> x = len(ops) - 1
85+
>>> y = len(ops[0]) - 1
86+
>>> assemble_transformation(ops, x, y)
87+
['Cc', 'Rau', 'Ct']
88+
89+
>>> ops1 = [['0']]
90+
>>> x1 = len(ops1) - 1
91+
>>> y1 = len(ops1[0]) - 1
92+
>>> assemble_transformation(ops1, x1, y1)
93+
[]
94+
"""
6195
if i == 0 and j == 0:
6296
return []
6397
elif ops[i][j][0] in {"C", "R"}:

0 commit comments

Comments
 (0)