I'm trying to implement Karger's algorithm for finding the minimum cut of a graph. The key part is the contract
method which performs a single contraction. Here is my implementation so far (with a 'test'):
import pytest
import random
class Graph(object):
def __init__(self, G):
self.G = G # Adjacency list
@property
def edges(self):
E = list()
for vertex in self.G:
for adjacent_vertex in self.G[vertex]:
if vertex < adjacent_vertex:
E.append([vertex, adjacent_vertex])
return E
def randomized_contract(self):
edge = random.choice(self.edges)
self.contract(edge)
def contract(self, edge):
vertex, adjacent_vertex = edge
self.G[vertex].remove(adjacent_vertex)
self.G[adjacent_vertex].remove(vertex)
self.G[vertex] += self.G[adjacent_vertex]
del self.G[adjacent_vertex]
for v in self.G:
for n, av in enumerate(self.G[v]):
if av == adjacent_vertex:
self.G[v][n] = vertex
self.remove_self_loops()
def remove_self_loops(self):
for vertex in self.G:
for n, adjacent_vertex in enumerate(self.G[vertex]):
if adjacent_vertex == vertex:
del self.G[vertex][n]
def contract_till_cut(self):
while len(self.G) > 2:
self.randomized_contract()
def test_contract_till_cut():
graph = Graph({1: [2,3], 2: [1,3], 3: [1,2,4], 4: [3]})
graph.contract_till_cut()
print(graph.G)
if __name__ == "__main__":
pytest.main([__file__, "-s"])
My problem is that on one particular run (you might have to run it a few times to reproduce this result), the get the adjacency list
{1: [1, 4], 4: [1]}
where node 1 has a 'self-loop' - that is, it occurs in its own adjacency list. I don't see how this can happen; every call to contract
is topped off by a call to remove_self_loops
which seems to work. Can anyone spot the bug in this code?
The problem was with the remove_self_loops
method: it was terminating after remove only one self-loop. I replaced it by the following:
def remove_self_loops(self):
for vertex in self.G:
self.G[vertex] = [av for av in self.G[vertex] if not av == vertex]
Now after the 'problem' case (which corresponds to contracting along edges [1,2]
and [1,3]
consecutively) I get the expected (minimum) cut:
{1: [4], 4: [1]}