Reputation: 703
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)
Upvotes: 0
Views: 688
Reputation: 7333
I think the problem may be the use of the is
keyword. Note that in python, is
only returns true when the two arguments refer to the exact same object (equivalent to char* == char*
in C++. The ==
operator returns true if the contents are the same (equivalent to string == string
in C++).
So rather than is not
try !=
.
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
:
links.add(frozenset(tuple(u | v))) if u in links or v in links else None
Upvotes: 1