[英]How should I create my object so it works with networkx pretty well?
我正在嘗試設計一個項目,該項目需要全球定位數據,例如城市和州名以及緯度和位置。 我還將在每兩座城市之間保持距離。 我想用所有這些信息制作一個圖,並對其進行操作以執行一些圖算法。 我決定要使用包含每個位置數據的城市對象。 現在我應該有一個散列函數來區分對象嗎? 我應該如何處理結合節點並去除邊的圖算法?
def minCut(self):
"""Returns the lowest-cost set of edges that will disconnect a graph"""
smcut = (float('infinity'), None)
cities = self.__selectedcities[:]
edges = self.__selectededges[:]
g = self.__makeGRAPH(cities, edges)
if not nx.is_connected(g):
print("The graph is already diconnected!")
return
while len(g.nodes()) >1:
stphasecut = self.mincutphase(g)
if stphasecut[2] < smcut:
smcut = (stphasecut[2], None)
self.__merge(g, stphasecut[0], stphasecut[1])
print("Weight of the min-cut: "+str(smcut[1]))
情況真的很糟。 我正在重寫原始程序,但這是我從以前的版本中采用的方法。
根據所安裝的networkx版本,可以使用min_cut的內置實現。
我安裝了1.0RC1軟件包,但該軟件包不可用。但是我升級到1.4,並且有min_cut。
這是一個(愚蠢的)示例:
import networkx as nx
g = nx.DiGraph()
g.add_nodes_from(['London', 'Boston', 'NY', 'Dallas'])
g.add_edge('NY', 'Boston', capacity)
g.add_edge('Dallas', 'Boston')
g.add_edge('Dallas', 'London')
# add capacity to existing edge
g.edge['Dallas']['London']['capacity'] = 2
# create edge with capacity attribute
g.add_edge('NY', 'London', capacity=3)
print nx.min_cut(g, 'NY', 'London')
您無需為城市對象創建哈希函數,您可以將城市對象直接傳遞給Networkx-從教程“節點可以是任何可哈希對象,例如文本字符串,圖像,XML對象,另一個圖,定制的節點對象等。”
您可以遍歷城市列表並將其添加為節點,然后遍歷距離信息以繪制圖表。
合並節點時,您可以創建新節點並將這些新節點散列到已合並的城市列表中。 例如,在上面的代碼中,您可以命名新節點len(g)並將其哈希化為stphasecut [0] + stphasecut [1]#假定stphasecut [1]和[2]是列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.