-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-friends.py
42 lines (33 loc) · 1.33 KB
/
find-friends.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def create_graph(network):
graph = {}
for link in network:
n1, n2 = tuple(link.split('-'))
graph[n1] = graph.get(n1, [])
graph[n2] = graph.get(n2, [])
graph[n1].append(n2)
graph[n2].append(n1)
return graph
def check_connection(network, first, second):
graph = create_graph(network)
visited = set()
def walk(item):
visited.add(item)
for link in graph[item]:
if link not in visited:
walk(link)
walk(first)
return second in visited
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert check_connection(
("dr101-mr99", "mr99-out00", "dr101-out00", "scout1-scout2",
"scout3-scout1", "scout1-scout4", "scout4-sscout", "sscout-super"),
"scout2", "scout3") == True, "Scout Brotherhood"
assert check_connection(
("dr101-mr99", "mr99-out00", "dr101-out00", "scout1-scout2",
"scout3-scout1", "scout1-scout4", "scout4-sscout", "sscout-super"),
"super", "scout2") == True, "Super Scout"
assert check_connection(
("dr101-mr99", "mr99-out00", "dr101-out00", "scout1-scout2",
"scout3-scout1", "scout1-scout4", "scout4-sscout", "sscout-super"),
"dr101", "sscout") == False, "I don't know any scouts."