Skip to content
Advertisement

A* search algorithm implementation in python

I am trying to build a very simple A* Search Algorithm in Python 3. Given the following distances for each node (considering S is the starting node and G the end one)

JavaScript

I want to write a function that finds the best path based on total cost (i.e., f(n) for those familiar with the terminology) for the following search space:

JavaScript

This is what I have written so far. The issue is that I cannot seem to implement dynamic programming. In other words, I cannot make it so that the algorithm selects the path having the lower f(n).

JavaScript

The function returns the following error:

JavaScript

I suspect I may be making some conceptual mistake here. Ay help would be appreciated!

Advertisement

Answer

Apparently you have some values in your cost dictionary that are of type None. Perhaps the previous_cost.get call returned None for some early value.

I might suggest a different approach. Rather than having separate collections for each piece of data used by A*, you should group them into objects. Make a node object that overrides __lt__ and pass in your f and g scores and your parent to its constructor.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement