Hi Team
I need some help with my python program, basically the instruction is as below;
// instructions from road system
Write a function that takes as arguments:
- A string representing JSON graph of the road system
- The starting intersection (node)
- The ending intersection (node)
And returns a dictionary containing information about the shortest path.
The return value should be a dictionary with keys distance and path.
distance should be the number that is the total sum of the distance metadata on each edge used.
path should be a list of integers, where each number is the id of a node used along the path from the start to the end.
// Code to do this all with test cases, getting an error after compiling
import json
from collections import deque
from typing import Dict, List, Tuple, Union
def parse_roads(roads) -> Dict[int, List[Tuple[int, Dict[str, float]]]]:
graph = {}
if isinstance(roads, str):
roads = json.loads(roads)
for road in roads:
if isinstance(road, tuple):
src, dest, distance = road
elif isinstance(road, dict):
src, dest, distance = road["src"], road["dest"], road["distance"]
else:
raise ValueError("Invalid input format")
metadata = {"distance": distance}
if src not in graph:
graph[src] = []
if dest not in graph:
graph[dest] = []
graph[src].append((dest, metadata))
graph[dest].append((src, metadata))
return graph
def navigate(roads: str, start: int, end: int) -> Dict[str, Union[int, List[int]]]:
graph = parse_roads(roads)
if start not in graph or end not in graph:
return {"error": "Starting or ending node not found in graph"}
distances = {node: float("inf") for node in graph}
previous_nodes = {node: None for node in graph}
distances[start] = 0
unvisited_nodes = set(graph)
while unvisited_nodes:
current_node = min(
unvisited_nodes, key=lambda node: distances[node]
)
unvisited_nodes.remove(current_node)
if distances[current_node] == float("inf"):
break
for neighbor, metadata in graph[current_node]:
alternative_route = distances[current_node] + metadata["distance"]
if alternative_route
in navigate
in parse_roads
ValueError: Invalid input format
Tuhin PaulRank #7 · 71.9K reputationPosted Mar 28, 2023, 4:11 PM EDT
Can you provide more information about the error you are getting?
Guest UserRank #877 · 2.5K reputationPosted Mar 29, 2023, 5:53 AM EDT
Hi Tulin
According to the error i am getting its not compiling is as below
/ Error when compiling ERROR: Traceback: in in navigate in parse_roads ValueError: Invalid input format