Created
November 4, 2011 21:48
-
-
Save larsyencken/1340574 to your computer and use it in GitHub Desktop.
Pathfinding for the ants problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def a_star_search(loc, dest, ants): | |
def cost_f(path): | |
return len(path) + ants.distance(path[-1], dest) | |
initial_path = (loc,) | |
frontier = [(cost_f(initial_path), initial_path)] | |
while frontier: | |
cost, path = frontier.pop() | |
if path[-1] == dest: | |
return path | |
for next_path in expand(path, ants): | |
frontier.append((cost_f(next_path), next_path)) | |
frontier.sort(reverse=True) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import deque | |
def breadth_first_search(loc, dest, ants): | |
queue = deque() | |
queue.append((loc,)) | |
while queue: | |
path = queue.popleft() | |
# goal test | |
if path[-1] == dest: | |
return path | |
for next_path in expand(path, ants): | |
queue.append(next_path) | |
# return failure |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def expand(path, ants): | |
loc = path[-1] | |
for neighbour in neighbours(loc, ants): | |
yield path + (neighbour,) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def greedy_search(loc, dest, ants): | |
def cost_f(path): | |
return ants.distance(path[-1], dest) | |
initial_path = (loc,) | |
frontier = [(cost_f(initial_path), initial_path)] | |
while frontier: | |
cost, path = frontier.pop() | |
if path[-1] == dest: | |
return path | |
for next_path in expand(path, ants): | |
frontier.append((cost_f(next_path), next_path)) | |
frontier.sort(reverse=True) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def neighbours(loc, ants): | |
for direction in ['n', 's', 'e', 'w']: | |
dest = ants.destination(loc, direction) | |
if ants.passable(dest): | |
yield dest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment