I am trying to write an output a result in a file in Python but it is not working neither it is showing any error.
Following is my code:
from collections import namedtuple
from pprint import pprint as pp
final_data = []
inf = float('inf')
Edge = namedtuple('Edge', 'start, end, cost')
class Graph():
def __init__(self, edges):
self.edges = edges2 = [Edge(*edge) for edge in edges]
self.vertices = set(sum(([e.start, e.end] for e in edges2), []))
def dijkstra(self, source, dest):
assert source in self.vertices
dist = {vertex: inf for vertex in self.vertices}
previous = {vertex: None for vertex in self.vertices}
dist[source] = 0
q = self.vertices.copy()
neighbours = {vertex: set() for vertex in self.vertices}
for start, end, cost in self.edges:
neighbours[start].add((end, cost))
#pp(neighbours)
while q:
u = min(q, key=lambda vertex: dist[vertex])
q.remove(u)
if dist[u] == inf or u == dest:
break
for v, cost in neighbours[u]:
alt = dist[u] + cost
if alt < dist[v]:
dist[v] = alt
previous[v] = u
#pp(previous)
s, u = [], dest
while previous[u]:
s.insert(0, u)
u = previous[u]
s.insert(0, u)
return s
start_point = input('Enter the starting point: ')
end_point = input('Enter the ending point: ')
file_name = input('Enter the input file name: ')
output_file = input('Enter the output file name: ')
f = open(file_name, 'r')
data = f.readlines()
for line in data:
f_line = line
values = f_line.split()
values[2] = int(values[2])
final_data.append(values)
graph = Graph(final_data)
f = open(output_file, 'a')
result = str(pp(graph.dijkstra(start_point, end_point)))
f.write(result)
Note: Ignore indentations
I am not sure where exactly i am making the mistake. I tried writing to the file using append(a) and write(w) but both did not work. All the paths to the files are correct and input file is reading perfectly and output file is also in the same folder.
f.close()at the end.pprint.pprintreturnsNone.pprint.pformat()