이 가중 에지 관한 그래프이다.
당신은 그것을 통해 경로를 탐색 할 수 Dijkstra's Algorithm 같은 것을 사용할 수 있습니다이 그래픽 표현을 생산
nestedg={1: {2: 3, 3: 8, 5: -4},
2: {4: 1, 5: 7},
3: {2: 4},
4: {1: 2, 3: -5},
5: {4: 6}}
with open('/tmp/graph.dot','w') as out:
for line in ('digraph G {','size="16,16";','splines=true;'):
out.write('{}\n'.format(line))
for start,d in nestedg.items():
for end,weight in d.items():
out.write('{} -> {} [ label="{}" ];\n'.format(start,end,weight))
out.write('}\n')
: 당신은 또한 당신의 특정 데이터를 시각화 할 수 graphviz를 사용할 수 있습니다. 예 사용이 특정 경로가 더 큰 '비용'을 갖는 라우팅 될 것이다 :
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if start not in graph:
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
def min_path(graph, start, end):
paths=find_all_paths(graph,start,end)
mt=10**99
mpath=[]
print '\tAll paths from {} to {}: {}'.format(start,end,paths)
for path in paths:
t=sum(graph[i][j] for i,j in zip(path,path[1::]))
print '\t\tevaluating: {}, cost: {}'.format(path, t)
if t<mt:
mt=t
mpath=path
e1=' '.join('{}->{}:{}'.format(i,j,graph[i][j]) for i,j in zip(mpath,mpath[1::]))
e2=str(sum(graph[i][j] for i,j in zip(mpath,mpath[1::])))
print 'Best path: '+e1+' Total: '+e2+'\n'
if __name__ == "__main__":
nestedg={1: {2: 3, 3: 8, 5: -4},
2: {4: 1, 5: 7},
3: {2: 4},
4: {1: 2, 3: -5},
5: {4: 6}}
min_path(nestedg,1,5)
min_path(nestedg,1,4)
min_path(nestedg,2,1)
데이터를 사용하여 그래프를 통해 몇 가지 예를 들어 경로는 다음과 같습니다
All paths from 1 to 5: [[1, 2, 5], [1, 3, 2, 5], [1, 5]]
evaluating: [1, 2, 5], cost: 10
evaluating: [1, 3, 2, 5], cost: 19
evaluating: [1, 5], cost: -4
Best path: 1->5:-4 Total: -4
All paths from 1 to 4: [[1, 2, 4], [1, 2, 5, 4], [1, 3, 2, 4], [1, 3, 2, 5, 4], [1, 5, 4]]
evaluating: [1, 2, 4], cost: 4
evaluating: [1, 2, 5, 4], cost: 16
evaluating: [1, 3, 2, 4], cost: 13
evaluating: [1, 3, 2, 5, 4], cost: 25
evaluating: [1, 5, 4], cost: 2
Best path: 1->5:-4 5->4:6 Total: 2
All paths from 2 to 1: [[2, 4, 1], [2, 5, 4, 1]]
evaluating: [2, 4, 1], cost: 3
evaluating: [2, 5, 4, 1], cost: 15
Best path: 2->4:1 4->1:2 Total: 3
당신의 사전 구조에서 왔는가 어디? 어느 쪽이든 : ** 1) ** 구조 자체를 정의했고 질문은 의문의 여지가 있거나 ** 2) ** 다른 누군가가 구조를 작성하고 그것이 나타내는 것을 문서화하지 못했습니다. 그 구조를 만들지 않고는 그것을 해석 할 방법이 없습니다. 너무 현지화 된 상태로 닫습니다. – Eric