我已经为这个问题写了一些代码。 (python27)
图表用冷冻集密钥和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])])}
输出应该是只有两个节点的图形,这两个节点是图形中所有节点的冻结点。此时它会遇到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)
答案 0 :(得分:1)
我认为问题可能是使用is
关键字。请注意,在python中,is
仅在两个参数引用 exact 相同对象(相当于C ++中的char* == char*
)时才返回true。==
运算符返回true如果内容相同(相当于C ++中的string == string
)。
而不是is not
尝试!=
。
在python中遍历图形中的元素时,曾经遇到过这个相同的问题。 :)
PS--另外,我将以下一行写为完整if
:
links.add(frozenset(tuple(u | v))) if u in links or v in links else None