Python - 圖表



圖是一種物件的集合的圖形表示,其中一些物件對透過連結連線。相互連線的物件由稱為頂點的點表示,連線頂點的連結稱為邊。與圖相關的各種術語和功能在本教程中進行了詳細描述。

在本章中,我們將瞭解如何使用 Python 程式建立圖並向其中新增各種資料元素。以下是我們在圖上執行的基本操作。

  • 顯示圖的頂點
  • 顯示圖的邊
  • 新增頂點
  • 新增邊
  • 建立圖

可以使用 Python 字典資料型別輕鬆地表示圖。我們將頂點表示為字典的鍵,並將頂點之間的連線(也稱為邊)表示為字典中的值。

看一下下面的圖 -

Array Declaration

在上圖中,

V = {a, b, c, d, e}
E = {ab, ac, bd, cd, de}

示例

我們可以在 Python 程式中如下表示此圖 -

# Create the dictionary with graph elements
graph = { 
   "a" : ["b","c"],
   "b" : ["a", "d"],
   "c" : ["a", "d"],
   "d" : ["e"],
   "e" : ["d"]
}
# Print the graph 		 
print(graph)

輸出

執行上述程式碼時,會產生以下結果 -

{'c': ['a', 'd'], 'a': ['b', 'c'], 'e': ['d'], 'd': ['e'], 'b': ['a', 'd']}

顯示圖的頂點

要顯示圖的頂點,我們只需找到圖字典的鍵。我們使用 keys() 方法。

class graph:
   def __init__(self,gdict=None):
      if gdict is None:
         gdict = []
      self.gdict = gdict
# Get the keys of the dictionary
   def getVertices(self):
      return list(self.gdict.keys())
# Create the dictionary with graph elements
graph_elements = { 
   "a" : ["b","c"],
   "b" : ["a", "d"],
   "c" : ["a", "d"],
   "d" : ["e"],
   "e" : ["d"]
}
g = graph(graph_elements)
print(g.getVertices())

輸出

執行上述程式碼時,會產生以下結果 -

['d', 'b', 'e', 'c', 'a']

顯示圖的邊

查詢圖的邊比查詢頂點稍微複雜一些,因為我們必須找到彼此之間存在邊的每對頂點。因此,我們建立一個空的邊列表,然後遍歷與每個頂點關聯的邊值。形成了一個包含從頂點找到的不同邊組的列表。

class graph:
   def __init__(self,gdict=None):
      if gdict is None:
         gdict = {}
      self.gdict = gdict

   def edges(self):
      return self.findedges()
# Find the distinct list of edges
   def findedges(self):
      edgename = []
      for vrtx in self.gdict:
         for nxtvrtx in self.gdict[vrtx]:
            if {nxtvrtx, vrtx} not in edgename:
               edgename.append({vrtx, nxtvrtx})
      return edgename
# Create the dictionary with graph elements
graph_elements = { 
   "a" : ["b","c"],
   "b" : ["a", "d"],
   "c" : ["a", "d"],
   "d" : ["e"],
   "e" : ["d"]
}
g = graph(graph_elements)
print(g.edges())

輸出

執行上述程式碼時,會產生以下結果 -

[{'b', 'a'}, {'b', 'd'}, {'e', 'd'}, {'a', 'c'}, {'c', 'd'}]

新增頂點

新增頂點很簡單,我們向圖字典新增另一個額外的鍵。

示例

class graph:
   def __init__(self,gdict=None):
      if gdict is None:
         gdict = {}
      self.gdict = gdict
   def getVertices(self):
      return list(self.gdict.keys())
# Add the vertex as a key
   def addVertex(self, vrtx):
      if vrtx not in self.gdict:
         self.gdict[vrtx] = []
# Create the dictionary with graph elements
graph_elements = { 
   "a" : ["b","c"],
   "b" : ["a", "d"],
   "c" : ["a", "d"],
   "d" : ["e"],
   "e" : ["d"]
}
g = graph(graph_elements)
g.addVertex("f")
print(g.getVertices())

輸出

執行上述程式碼時,會產生以下結果 -

['a', 'b', 'c', 'd', 'e','f']

新增邊

向現有圖新增邊涉及將新頂點視為元組,並驗證邊是否已存在。如果不存在,則新增邊。

class graph:
   def __init__(self,gdict=None):
      if gdict is None:
         gdict = {}
      self.gdict = gdict
   def edges(self):
      return self.findedges()
# Add the new edge
   def AddEdge(self, edge):
      edge = set(edge)
      (vrtx1, vrtx2) = tuple(edge)
      if vrtx1 in self.gdict:
         self.gdict[vrtx1].append(vrtx2)
      else:
         self.gdict[vrtx1] = [vrtx2]
# List the edge names
   def findedges(self):
      edgename = []
      for vrtx in self.gdict:
         for nxtvrtx in self.gdict[vrtx]:
            if {nxtvrtx, vrtx} not in edgename:
               edgename.append({vrtx, nxtvrtx})
        return edgename
# Create the dictionary with graph elements
graph_elements = { 
   "a" : ["b","c"],
   "b" : ["a", "d"],
   "c" : ["a", "d"],
   "d" : ["e"],
   "e" : ["d"]
}
g = graph(graph_elements)
g.AddEdge({'a','e'})
g.AddEdge({'a','c'})
print(g.edges())

輸出

執行上述程式碼時,會產生以下結果 -

[{'e', 'd'}, {'b', 'a'}, {'b', 'd'}, {'a', 'c'}, {'a', 'e'}, {'c', 'd'}]
廣告