Created
February 11, 2015 04:19
-
-
Save niklio/a51ca0950f984d8cb13b to your computer and use it in GitHub Desktop.
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
import wikipedia, sys | |
def AStar(start, goal): | |
closedset = [] | |
openset = [trypage(link) for link in start.links] | |
navigated = {} | |
g_score = lambda start: 0 | |
f_score = lambda start: g_score(start) + heuristic_cost(start, goal) | |
while openset != []: | |
current = sorted([(f_score, link) for link in openset], reverse=True)[0][1] | |
print current | |
if current == goal: | |
return reconstruct_path(navigated, goal) | |
openset.remove(current) | |
closedset.append(current) | |
for neighbor in [trypage(link) for link in current.links]: | |
if neighbor in closedset: | |
break | |
tentative_g_score = g_score(current) | |
if neighbor not in openset: | |
navigated[neighbor.title] = current.title | |
if neighbor not in openset: | |
openset.append(neighbor) | |
return None | |
def reconstruct_path(came_from, current): | |
total_path = [current] | |
while current in came_from: | |
current = came_from[current] | |
total_path.append(current) | |
return total_path | |
def heuristic_cost(start, goal): | |
return 0 | |
def trypage(link): | |
try: | |
return wikipedia.page(link) | |
except wikipedia.exceptions.PageError: | |
return None | |
except wikipedia.exceptions.DisambiguationError: | |
return None | |
if __name__ == '__main__': | |
if len(sys.argv) > 1: | |
first = wikipedia.page(sys.argv[1]) | |
else: | |
first = wikipedia.page(wikipedia.random()) | |
goal = wikipedia.page('Adolf Hitler') | |
AStar(first, goal) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment