Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

a star search algorithm python code

def heuristic(a: GridLocation, b: GridLocation) -> float:
    (x1, y1) = a
    (x2, y2) = b
    return abs(x1 - x2) + abs(y1 - y2)

def a_star_search(graph: WeightedGraph, start: Location, goal: Location):
    frontier = PriorityQueue()
    frontier.put(start, 0)
    came_from: Dict[Location, Optional[Location]] = {}
    cost_so_far: Dict[Location, float] = {}
    came_from[start] = None
    cost_so_far[start] = 0
    
    while not frontier.empty():
        current: Location = frontier.get()
        
        if current == goal:
            break
        
        for next in graph.neighbors(current):
            new_cost = cost_so_far[current] + graph.cost(current, next)
            if next not in cost_so_far or new_cost < cost_so_far[next]:
                cost_so_far[next] = new_cost
                priority = new_cost + heuristic(next, goal)
                frontier.put(next, priority)
                came_from[next] = current
    
    return came_from, cost_so_far
Comment

PREVIOUS NEXT
Code Example
Python :: compare string python 
Python :: create database tables python 
Python :: how to stop python for some time in python 
Python :: How to build a Least Recently Used (LRU) cache, in Python? 
Python :: wails install 
Python :: how to scan directory recursively python 
Python :: numpy variance 
Python :: python can you put try except in list comprehension 
Python :: permutation and combination in python 
Python :: how to encode a string in python 
Python :: get image image memeory size in url inpyton requests 
Python :: install requests-html with conda 
Python :: set lable of field django 
Python :: create instances of a class in a for loop 
Python :: extract specific key values from nested dictionary 
Python :: get last x elements of list python 
Python :: python filter list 
Python :: variable bound to a set python 
Python :: statsmodels fitted values 
Python :: python print ling line in print 
Python :: any() and all() 
Python :: django filter values with OR operator 
Python :: create folders in python overwright existing 
Python :: python using list as dictionary key 
Python :: python subtract between list 
Python :: how to find min, max in dictionaries 
Python :: how to set environment variable in pycharm 
Python :: python open file location 
Python :: python get bits from byte 
Python :: try except to specific line 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =