图论的圣人,KeyError

时间:2015-08-10 20:22:44

标签: python sage

我将从我的代码开始,因为对于那些对语言有更好理解的人来说,这可能只是一个明显的问题:

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 个答案:

答案 0 :(得分:1)

我明白了!事实证明,错误来自于具有在new_strong中没有意义的条目,即已经删除的顶点的条目。当plot()尝试根据d

对顶点着色时,这会导致键错误