Last active
December 31, 2019 13:33
-
-
Save dktn/c2d5bc57fb330ce6e4bdf551272deb73 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
# from a book Grokking Algorithms | |
from collections import deque | |
graph = {} | |
graph["you"] = ["alice", "bob", "claire"] | |
graph["bob"] = ["anuj", "peggy"] | |
graph["alice"] = ["peggy"] | |
graph["claire"] = ["thom", "johny"] | |
graph["anuj"] = [] | |
graph["peggy"] = [] | |
graph["thom"] = [] | |
graph["johny"] = [] | |
search_deque = deque() | |
search_deque += graph["you"] | |
def person_is_seller(name): | |
return name[-1] == 'm' | |
def search(name): | |
search_queue = deque() | |
search_queue += graph[name] | |
searched = [] | |
while search_queue: | |
person = search_queue.popleft() | |
if not person in searched: | |
if person_is_seller(person): | |
print(person + " is mango seller!") | |
return True | |
else: | |
search_queue += graph[person] | |
searched.append(person) | |
print("No mango seller found!") | |
return False | |
search("you") | |
search("bob") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment