I’ve written some code for this problem. (python27)
Graph is represented as dictionary with frozenset keys and sets of frozensets:
sample_graph = {frozenset([7]): set([frozenset([4]), frozenset([5]), frozenset([3])]), frozenset([5]): set([frozenset([7]), frozenset([2]), frozenset([1])]), frozenset([3]): set([frozenset([7]), frozenset([4]), frozenset([2]), frozenset([1])]), frozenset([6]): set([frozenset([4]), frozenset([2]), frozenset([1])]), frozenset([4]): set([frozenset([6]), frozenset([7]), frozenset([3]), frozenset([1])]), frozenset([1]): set([frozenset([6]), frozenset([4]), frozenset([5]), frozenset([2]), frozenset([3])]), frozenset([2]): set([frozenset([6]), frozenset([5]), frozenset([3]), frozenset([1])])}
Output should be a graph with only two nodes which are the frozensets of all the nodes in the graph. At this point it runs into KeyError.
def kargerMinCut(graph):
if len(graph) == 2:
return graph
u = random.choice(graph.keys()) # u and v are frozensets, idea is that they form
v = random.choice(list(graph[u])) # a clique in a single frozenset
for node in graph:
if node != u and node != v:
links = graph[node]
if u in links or v in links:
links.add(frozenset(tuple(u | v))) # combine u and v to form one link
links.discard(u) # delete old links to u and v
links.discard(v)
graph[node] = links
graph[u | v] = graph[u] | graph[v] # new key for u and v
del graph[u], graph[v] # u and v are no longer needed
return kargerMinCut(graph)
I think the problem may be the use of the
iskeyword. Note that in python,isonly returns true when the two arguments refer to the exact same object (equivalent tochar* == char*in C++. The==operator returns true if the contents are the same (equivalent tostring == stringin C++).So rather than
is nottry!=.I once had this identical problem when traversing elements in a graph in python. : )
PS– Also, I’d write the following line as a full
if: