【发布时间】:2020-05-26 05:22:51
【问题描述】:
我正在尝试解决 Dijkstra 算法的问题。基本上,我想随机选择开始和结束节点,并在配对节点并运行算法后找到每条路径的距离。最后,我想将结果保存为列表。到目前为止,代码运行良好,但是,我在将结果保存为列表时遇到了挑战。 这是我使用的代码。
import random
from random import seed
from random import random
from random import randint
import pandas as pd
import numpy as np
import statistics
distance = [(0,7,3,0,0),(7,0,1,2,6),(3,1,0,2,0),(0,2,2,0,4),(0,6,0,4,0)]
dist = np.array(distance)
graph = dist
# Python program for Dijkstra's
from collections import defaultdict
class Graph:
def minDistance(self,dist,queue):
minimum = float("Inf")
min_index = -1
for i in range(len(dist)):
if dist[i] < minimum and i in queue:
minimum = dist[i]
min_index = i
return min_index
def printPath(self, parent, end):
if parent[end] == -1 :
#print (end),
return
self.printPath(parent , parent[end])
#print (end),
def printSolution(self, dist, parent):
#print("Vertex and Path \t\tDistance from Source")
#print((start, end, dist[end])), self.printPath(parent,end) #if you want to see start and end nodes
print(dist[end]), self.printPath(parent,end) #if you do not want to see start and end nodes
'''Function that implements Dijkstra's single source shortest path
algorithm for a graph represented using adjacency matrix
representation'''
def dijkstra(self, graph, start):
row = len(graph)
col = len(graph[0])
dist = [float("Inf")] * row
parent = [-1] * row
dist[start] = 0
queue = []
for i in range(row):
queue.append(i)
while queue:
u = self.minDistance(dist,queue)
queue.remove(u)
for i in range(col):
'''Update dist[i] only if it is in queue, there is
an edge from u to i, and total weight of path from
start to i through u is smaller than current value of
dist[i]'''
if graph[u][i] and i in queue:
if dist[u] + graph[u][i] < dist[i]:
dist[i] = dist[u] + graph[u][i]
parent[i] = u
self.printSolution(dist,parent)
g= Graph()
seed(1)
start1 = []
for x in range(3):
start = randint(0, 3)
start1.append(start)
seed(3)
end1 = []
for x in range(3):
end = randint(2,4)
end1.append(end)
start = start1
end = end1
results = []
for i in start1:
for q in end1:
start = i
end = q
if i != q:
results.append(g.dijkstra(graph,i))
上面的代码产生了这个结果...
1
6
6
3
9
9
6
6
当我调用保存的列表时,我得到“无”值。
results
[None, None, None, None, None, None, None, None]
我希望得到如下结果:
[1,6,6,3,9,9,6,6,]
由于我是使用 python 的初学者,如果有人可以帮助我将结果保存为列表,我将非常感激。
【问题讨论】:
标签: python python-3.x python-2.7 python-requests dijkstra