2017-07-16 39 views
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!") 

我的問題是因爲我使用的套一本字典,既可以在

引發KeyError
self.vertices[x].remove(y) 

如果我想打印指示那些兩個頂點(xy)中的一個不存在的錯誤信息,有確定所述線的一部分引發的錯誤的方法嗎?或者我必須再次檢查並將錯誤信息從(重複)檢查中刪除?

(注:我認識到,是在代碼中的一些邏輯錯誤之上 - 例如,的add_edge需要檢查x和y都存在)

+1

拆分成兩個語句知道: 'temp = self.vertices [x]'和'temp.remove(y)',每個都在單獨的'try'塊中。 – jasonharper

+0

@jasonharper:隨意做出答案 - 如果沒有人提出更短/仍然容易閱讀的內容,我會接受它。 – tonysdg

+1

爲什麼您的圖表類負責打印錯誤消息?如果重新添加現有邊或者移除不存在的邊或任何其他邊的錯誤,看起來您的圖應該通過異常來進行通信。 – user2357112

回答

1

所以第一隻檢查是否有出現任何節點命名爲X在圖中,如果它存在,則檢查是否有存在的邊從X到Y

def remove_edge(self, x, y): 
    """ Removes the edge from x to y, if it exists """  
    if x in self.vertices: 
     if y in self.vertices[x]: 
      self.vertices[x].remove(y) 
     else: 
      print("There is no edge from x to y") 
    else: 
     print("There is no node x present in the graph") 

,如果你真的想根據試捕

def remove_edge(self, x, y): 
    """ Removes the edge from x to y, if it exists """ 

    try: 
     self.vertices[x] 
    except KeyError: 
     print("Error: vertex x not found!") 

    try: 
     self.vertices[x].remove(y) 
    except KeyError: 
     print("Error: vertex y not found!")