Sage for Graph Theory, KeyError

3

我先说一下我的代码,因为这可能只是对那些更好理解语言的人来说显而易见的问题:

g = graphs.CompleteGraph(60).complement()
for i in range(1,180):
    a = randint(0,59)
    b = randint(0,59)
    h = copy(g)
    h.add_edge(a,b)
    if h.is_circular_planar():
        g.add_edge(a,b)

strong = copy(strong_resolve(g))
S = strong.vertex_cover()
d = {'#00FF00': [], '#FF0000': []}
for v in G.vertices():
    if v in S:
        d['#FF0000'].append(v)
    else:
        d['#00FF00'].append(v)
g.plot(layout="spring", vertex_colors=d).show()     
strong.plot(vertex_colors=d).show()

new_strong = copy(strong)
for w in new_strong.vertices():
    if len(new_strong.neighbors(w)) == 0:          #trying to remove
        new_strong.delete_vertex(w)                #disconnected vertices
new_strong.plot(vertex_colors=d).show()

一些注意事项:strong_resolve是一个函数,它接受一个图形并输出另一个图形。前两个代码块运行良好。

我的问题是,一旦添加第三个代码块,事情就不再起作用了。在瞎弄时,我得到了这段代码的变体,当添加时会导致错误,并且当删除时错误仍然存在。现在发生的是,for循环似乎会一直执行直到最后,然后才会出现以下错误:

Traceback (most recent call last):        if h.is_circular_planar():
  File "", line 1, in <module>

  File "/tmp/tmprzreop/___code___.py", line 30, in <module>
    exec compile(u'new_strong.plot(vertex_colors=d).show()
  File "", line 1, in <module>

  File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/misc/decorators.py", line 550, in wrapper
    return func(*args, **options)
  File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/generic_graph.py", line 15706, in plot
    return self.graphplot(**options).plot()
  File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/generic_graph.py", line 15407, in graphplot
    return GraphPlot(graph=self, options=options)
  File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/graph_plot.py", line 247, in __init__
    self.set_vertices()
  File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/graph_plot.py", line 399, in set_vertices
    pos += [self._pos[j] for j in vertex_colors[i]]
KeyError: 0

这可能有所不同,即KeyError: 0 偶尔会是1或2,具体取决于某些未知因素。

我很抱歉代码写得很糟糕,并承认我真的不知道自己在做什么,但如果有人能帮我解决这个问题,我会非常感激。

1个回答

1
我明白了!原来错误是由于d中有一些在new_strong中没有意义的条目,即那些已被删除的顶点。这导致plot()在根据d对顶点着色时出现键错误。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接