Skip to content
Closed
Changes from 1 commit
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
37 changes: 37 additions & 0 deletions data_structures/Prim’s-Algorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import heapq

Check failure on line 1 in data_structures/Prim’s-Algorithm.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

data_structures/Prim’s-Algorithm.py:1:1: I001 Import block is un-sorted or un-formatted

Check failure on line 1 in data_structures/Prim’s-Algorithm.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N999)

data_structures/Prim’s-Algorithm.py:1:1: N999 Invalid module name: 'Prim’s-Algorithm'

def prim_mst(graph, start=0):
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file data_structures/Prim’s-Algorithm.py, please provide doctest for the function prim_mst

Please provide return type hint for the function: prim_mst. If the function does not return a value, please provide the type hint as: def function() -> None:

Please provide type hint for the parameter: graph

Please provide type hint for the parameter: start

visited = set()
mst = []
total_cost = 0

# Min-heap (cost, current_node, next_node)
edges = [(0, start, start)]

while edges:
cost, u, v = heapq.heappop(edges)
if v in visited:
continue
visited.add(v)
total_cost += cost
if u != v:
mst.append((u, v, cost))
for neighbor, weight in graph[v]:
if neighbor not in visited:
heapq.heappush(edges, (weight, v, neighbor))

return mst, total_cost


# Example Graph as adjacency list
graph = {
0: [(1, 2), (3, 6)],
1: [(0, 2), (2, 3), (3, 8), (4, 5)],
2: [(1, 3), (4, 7)],
3: [(0, 6), (1, 8)],
4: [(1, 5), (2, 7)]
}

mst, cost = prim_mst(graph)
print("Edges in MST:", mst)
print("Total Cost:", cost)
Loading