Created
February 12, 2017 20:40
-
-
Save sangheestyle/a13e0c16069ef8abfdb49d089d962af9 to your computer and use it in GitHub Desktop.
Chapter 6, Breath-first search (From Grokking Algorithm)
This file contains hidden or 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 is_person_seller(person): | |
return True if person.endswith('m') else False | |
def search(graph, start_point, search_function): | |
search_queue = deque() | |
search_queue.extend(graph[start_point]) | |
visited = [] | |
while search_queue: | |
person = search_queue.popleft() | |
if person in visited: | |
continue | |
else: | |
visited.append(person) | |
if search_function(person): | |
return person | |
else: | |
search_queue += graph[person] | |
return None | |
test_graph = { | |
'me': ['you'], | |
'you': [], | |
'she': ['him'], | |
'him': [] | |
} | |
assert search(test_graph, 'me', is_person_seller) == None | |
assert search(test_graph, 'you', is_person_seller) == None | |
assert search(test_graph, 'she', is_person_seller) == 'him' | |
assert search(test_graph, 'him', is_person_seller) == None | |
graph = {} | |
graph['bob'] = ['anuj', 'peggy'] | |
graph['you'] = ['alice', 'bob', 'claire'] | |
graph['alice'] = ['peggy'] | |
graph['claire'] = ['thom', 'jonny'] | |
graph['anuj'] = [] | |
graph['peggy'] = [] | |
graph['thom'] = [] | |
graph['jonny'] = [] | |
seller = search(graph, 'you', is_person_seller) | |
print("Seller is {}".format(seller if seller else "nobody")) | |
#Seller is thom |
Need to do more:
- Print shortest path. For example, in this case,
You -> Claire -> Thom
should be the answer.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://docs.python.org/2/library/collections.html#collections.deque