我需要建立這樣的基於用戶輸入代表向加權圖在Python創建權圖 -基於用戶輸入
graph = {
'a': {'b': 1, 'c': 4},
'b': {'c': 3, 'd': 2, 'e': 2},
'c': {},
'd': {'b': 1, 'c': 5},
'e': {'d': -2}
}
到目前爲止,
import pprint
graph = {}
values = {}
v = int(input("Enter number of vertices: "))
print("Enter vertices(keys) : ")
for i in range(v):
graph.setdefault(input())
edges = {}
for x in graph:
edges.setdefault(x)
for i in graph:
graph[i] = edges
print("Enter weights: ")
for i in graph:
print(i)
for j in graph[i]:
var = input()
graph[i][j] = var
pprint.pprint(graph)
我試着但由於某些原因,它將用上次讀取的權重替換先前讀取的權重。任何解決方案
任何企圖這麼遠? –
你既沒有顯示你的輸入格式也沒有嘗試,但看看是否有幫助:http://stackoverflow.com/questions/38165292/how-to-convert-an-adjacency-matrix-to-an-adjacency-list -with-python/38165410#38165410 –
而不是重新發明輪子 - 你可能想看看https://networkx.github.io/ –