2016-11-30 223 views
1

我是新來的stackoverflow。我搜索了適合我的問題的主題,但不幸的是我沒有找到一個。所以我開了一個新話題。創建矩陣

我必須在python中實現一個函數,該函數創建出某個輸入的關聯矩陣。我的問題是,我不太明白如何訪問indeces,所以每列只有一個'1'而不是兩個..:/

希望你們可以幫助我.. kinda丟失我的介意這一個

class incidence_matrix: 
    def __init__(self, vertices, edges): 
     self.vertices = vertices 
     self.edges = edges 
     self.liste = [[0 for i in range(vertices)] for i in range(vertices)] 
     #print(self.liste) 
     for i in range(0, vertices): 
      for j in range(0, len(edges)): 
       if edges[i][j-1] >= vertices or edges[i][j-1] < 0 or edges[i][j-1] >= vertices or edges[i][j-1] < 0: 
        print("Index out of range") 
        return 
       self.liste[edges[0][j+1]][edges[1][j+1]] = 1 
       self.liste[edges[1][j+1]][edges[0][j+1]] = 1 

     for x in range(0, vertices): 
      row = "" 
      for y in range(0, len(edges)): 
       row = row + str(self.liste[x][y]) + " " 
      print(row) 
+0

你能告訴邊緣字典樣子 – Navidad20

+0

圖表= incidence_matrix(4,[(1,2),(0, 1),(0,2)]) –

回答

0

這應該適合你。它假定邊是雙向的。

class incidence_matrix: 
    def __init__(self, vertices, edges): 
     self.vertices = vertices 
     self.edges = edges 
     self.liste = [[0 for i in range(vertices)] for i in range(len(edges))] 
     for i in range(len(edges)): 
      v1, v2 = edges[i] 
      if v1 >= vertices: 
       continue 
      if v2 >= vertices: 
       continue 
      self.liste[i][v1] = 1 
      self.liste[i][v2] = 1 

     for i in range(len(edges)): 
      row = ' '.join([str(x) for x in self.liste[i]]) 
      print(row) 

輸入:

graph = incidence_matrix(4, [(1,2),(0,1),(0,2)]) 

輸出:

0 1 1 0 
1 1 0 0 
1 0 1 0 
+0

mh ...這不是正確的輸出。我不知道如何格式化聊天輸入以顯示矩陣,但程序的輸出必須是 [[0,1,1] [1,1,0] [1,0,1] [ 0,0,0]]但它是[[0,1,1,0] [0,0,1,0] [0,0,0,0] [0,0,0,0]] –

+0

I如果你把4個頂點放在一起,你會不會想要每對之間的匹配? – Navidad20

+0

是的,我只是作爲Matrix的發病率而已。你給我的輸出是一個鄰接矩陣 - 或者我現在錯了..? –