Skip to content

Commit 94ee127

Browse files
committed
changed the addressed errors and fixed the main error
1 parent 6a40f5c commit 94ee127

File tree

2 files changed

+59
-9
lines changed

2 files changed

+59
-9
lines changed

pydatastructs/graphs/algorithms.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -744,8 +744,11 @@ def shortest_paths(graph: Graph, algorithm: str,
744744
>>> G2 = Graph(start, middle, goal)
745745
>>> G2.add_edge('0,0', '1,1', 2)
746746
>>> G2.add_edge('1,1', '2,2', 2)
747-
>>> shortest_paths(G2, 'a_star', '0,0', '2,2')
748-
(4, {'0,0': None, '1,1': '0,0', '2,2': '1,1'})
747+
>>> dist, pred = shortest_paths(G2, 'a_star', '0,0', '2,2')
748+
>>> dist
749+
4
750+
>>> pred == {'0,0': None, '1,1': '0,0', '2,2': '1,1'}
751+
True
749752
References
750753
==========
751754
@@ -852,19 +855,20 @@ def heuristic(node: str, goal: str) -> float:
852855
pred = {v: None for v in graph.vertices}
853856
dist[source] = 0
854857
from pydatastructs.miscellaneous_data_structures.queue import PriorityQueue, BinomialHeapPriorityQueue
855-
pq = PriorityQueue(implementation='binomial_heap')
858+
pq = PriorityQueue(implementation='binomial_heap')
856859
f_score = heuristic(source, target)
857860
pq.push(source, f_score)
858-
while not pq.is_empty:
861+
while not pq.is_empty:
859862
current = pq.pop()
860863
if current == target:
861-
return dist[target], pred
864+
result = (dist[target], dict(sorted(pred.items())))
865+
return result
862866
if visited[current]:
863867
continue
864-
visited[current] = True
868+
visited[current] = True
865869
neighbors = graph.neighbors(current)
866870
if not neighbors:
867-
continue
871+
continue
868872
for neighbor in neighbors:
869873
if visited[neighbor.name]:
870874
continue
@@ -877,7 +881,9 @@ def heuristic(node: str, goal: str) -> float:
877881
pred[neighbor.name] = current
878882
f_score = new_dist + heuristic(neighbor.name, target)
879883
pq.push(neighbor.name, f_score)
880-
return float('inf'), pred
884+
if dist[target] == float('inf'):
885+
raise ValueError(f"Either source '{source}' and target '{target}' have no path between them.")
886+
return float('inf'), dict(sorted(pred.items()))
881887
_a_star_adjacency_matrix = _a_star_adjacency_list
882888
def all_pair_shortest_paths(graph: Graph, algorithm: str,
883889
**kwargs) -> tuple:

pydatastructs/graphs/tests/test_algorithms.py

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import pytest
12
from pydatastructs import (breadth_first_search, Graph,
23
breadth_first_search_parallel, minimum_spanning_tree,
34
minimum_spanning_tree_parallel, strongly_connected_components,
@@ -314,13 +315,56 @@ def _test_shortest_paths_negative_edges(ds, algorithm):
314315
dist, pred = shortest_paths(graph, algorithm, 's', 'd')
315316
assert dist == 2
316317
assert pred == {'s': None, 'a': 'b', 'b': 's', 'c': 'a', 'd': 'c'}
317-
318+
def _test_a_star_manhattan(ds):
319+
import pydatastructs.utils.misc_util as utils
320+
GraphNode = getattr(utils, "Adjacency" + ds + "GraphNode")
321+
vertices = [
322+
GraphNode("0,0"),
323+
GraphNode("1,1"),
324+
GraphNode("2,2")
325+
]
326+
graph = Graph(*vertices)
327+
graph.add_edge("0,0", "1,1", 2)
328+
graph.add_edge("1,1", "2,2", 2)
329+
distance, pred = shortest_paths(graph, 'a_star', "0,0", "2,2")
330+
assert distance == 4
331+
assert pred == {'0,0': None, '1,1': '0,0', '2,2': '1,1'}
332+
no_path_graph = Graph(
333+
GraphNode("0,0"),
334+
GraphNode("1,1"),
335+
GraphNode("2,2")
336+
)
337+
with pytest.raises(ValueError, match="Either source '0,0' and target '2,2' have no path between them."):
338+
shortest_paths(no_path_graph, 'a_star', "0,0", "2,2")
339+
same_node_graph = Graph(GraphNode("1,1"))
340+
distance, pred = shortest_paths(same_node_graph, 'a_star', "1,1", "1,1")
341+
assert distance == 0
342+
assert pred == {'1,1': None}
343+
invalid_graph = Graph(GraphNode("invalid"))
344+
with pytest.raises(ValueError, match="Invalid node format: invalid. Expected 'x,y'."):
345+
shortest_paths(invalid_graph, 'a_star', "invalid", "invalid")
346+
complex_vertices = [
347+
GraphNode("0,0"),
348+
GraphNode("0,1"),
349+
GraphNode("1,0"),
350+
GraphNode("1,1")
351+
]
352+
complex_graph = Graph(*complex_vertices)
353+
complex_graph.add_edge("0,0", "0,1", 1)
354+
complex_graph.add_edge("0,1", "1,1", 1)
355+
complex_graph.add_edge("0,0", "1,0", 2)
356+
complex_graph.add_edge("1,0", "1,1", 1)
357+
distance, pred = shortest_paths(complex_graph, 'a_star', "0,0", "1,1")
358+
assert distance == 2
359+
assert pred == {'0,0': None, '0,1': '0,0', '1,1': '0,1', '1,0': '0,0'}
318360
_test_shortest_paths_positive_edges("List", 'bellman_ford')
319361
_test_shortest_paths_positive_edges("Matrix", 'bellman_ford')
320362
_test_shortest_paths_negative_edges("List", 'bellman_ford')
321363
_test_shortest_paths_negative_edges("Matrix", 'bellman_ford')
322364
_test_shortest_paths_positive_edges("List", 'dijkstra')
323365
_test_shortest_paths_positive_edges("Matrix", 'dijkstra')
366+
_test_a_star_manhattan("List")
367+
_test_a_star_manhattan("Matrix")
324368

325369
def test_all_pair_shortest_paths():
326370

0 commit comments

Comments
 (0)