1
我正在使用一個鄰接表在Python 3.x中編寫一個(定向)圖的簡單實現。要刪除圖形的邊緣,我看,看起來像這樣的功能:如何確定KeyError的來源?
class Graph(object):
def __init__(self):
self.vertices = {}
def add_vertex(self, x):
""" Adds x to the graph, if it doesn't exist """
if x not in self.vertices:
self.vertices[x] = set()
else:
print("Error: vertex {} already in graph!".format(x))
def add_edge(self, x, y):
""" Adds the edge from x to y, if it doesn't exist """
try:
if y not in self.vertices[x]:
self.vertices[x].add(y)
else:
print("Error: edge already exists!")
except KeyError:
print("Error: vertex {} not found!".format(x))
def remove_edge(self, x, y):
""" Removes the edge from x to y, if it exists """
try:
self.vertices[x].remove(y)
except KeyError:
# QUESTION: which part of the try block caused the KeyError?
print("Error: vertex not found!")
我的問題是因爲我使用的套一本字典,既可以在
引發KeyErrorself.vertices[x].remove(y)
如果我想打印指示那些兩個頂點(x
或y
)中的一個不存在的錯誤信息,有確定所述線的一部分引發的錯誤的方法嗎?或者我必須再次檢查並將錯誤信息從(重複)檢查中刪除?
(注:我認識到,是在代碼中的一些邏輯錯誤之上 - 例如,的add_edge需要檢查x和y都存在)
拆分成兩個語句知道: 'temp = self.vertices [x]'和'temp.remove(y)',每個都在單獨的'try'塊中。 – jasonharper
@jasonharper:隨意做出答案 - 如果沒有人提出更短/仍然容易閱讀的內容,我會接受它。 – tonysdg
爲什麼您的圖表類負責打印錯誤消息?如果重新添加現有邊或者移除不存在的邊或任何其他邊的錯誤,看起來您的圖應該通過異常來進行通信。 – user2357112