code for chapter 6
This commit is contained in:
34
06_breadth-first_search/python/01_breadth-first_search.py
Normal file
34
06_breadth-first_search/python/01_breadth-first_search.py
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
from collections import deque
|
||||||
|
|
||||||
|
def person_is_seller(name):
|
||||||
|
return name[-1] == 'm'
|
||||||
|
|
||||||
|
graph = {}
|
||||||
|
graph["you"] = ["alice", "bob", "claire"]
|
||||||
|
graph["bob"] = ["anuj", "peggy"]
|
||||||
|
graph["alice"] = ["peggy"]
|
||||||
|
graph["claire"] = ["thom", "jonny"]
|
||||||
|
graph["anuj"] = []
|
||||||
|
graph["peggy"] = []
|
||||||
|
graph["thom"] = []
|
||||||
|
graph["jonny"] = []
|
||||||
|
|
||||||
|
def search(name):
|
||||||
|
search_queue = deque()
|
||||||
|
search_queue += graph[name]
|
||||||
|
# This array is how you keep track of which people you've searched before.
|
||||||
|
searched = []
|
||||||
|
while search_queue:
|
||||||
|
person = search_queue.popleft()
|
||||||
|
# Only search this person if you haven't already searched them.
|
||||||
|
if not person in searched:
|
||||||
|
if person_is_seller(person):
|
||||||
|
print person + " is a mango seller!"
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
search_queue += graph[person]
|
||||||
|
# Marks this person as searched
|
||||||
|
searched.append(person)
|
||||||
|
return False
|
||||||
|
|
||||||
|
search("you")
|
||||||
Reference in New Issue
Block a user