system-design-primer/solutions/system_design/social_graph/social_graph_snippets.py

73 lines
1.7 KiB
Python
Raw Normal View History

2017-03-05 08:06:28 +03:00
# -*- coding: utf-8 -*-
from collections import deque
from enum import Enum
2021-03-14 13:08:05 +03:00
class State(Enum) :
unvisited = 0
visited = 1
2017-03-05 08:06:28 +03:00
2021-03-14 13:08:05 +03:00
class Graph(object) :
2017-03-05 08:06:28 +03:00
2021-03-14 13:08:05 +03:00
def bfs(self, source, dest) :
2017-03-05 08:06:28 +03:00
if source is None:
return False
2021-03-14 13:08:05 +03:00
queue = deque()
queue.append(source)
2017-03-05 08:06:28 +03:00
source.visit_state = State.visited
while queue:
2021-03-14 13:08:05 +03:00
node = queue.popleft()
print(node)
2017-03-05 08:06:28 +03:00
if dest is node:
return True
2021-03-14 13:08:05 +03:00
for adjacent_node in node.adj_nodes.values() :
2017-03-05 08:06:28 +03:00
if adjacent_node.visit_state == State.unvisited:
2021-03-14 13:08:05 +03:00
queue.append(adjacent_node)
2017-03-05 08:06:28 +03:00
adjacent_node.visit_state = State.visited
return False
2021-03-14 13:08:05 +03:00
class Person(object) :
2017-03-05 08:06:28 +03:00
2021-03-14 13:08:05 +03:00
def __init__(self, id, name) :
2017-03-05 08:06:28 +03:00
self.id = id
self.name = name
self.friend_ids = []
2021-03-14 13:08:05 +03:00
class LookupService(object) :
2017-03-05 08:06:28 +03:00
2021-03-14 13:08:05 +03:00
def __init__(self) :
2017-03-05 08:06:28 +03:00
self.lookup = {} # key: person_id, value: person_server
2021-03-14 13:08:05 +03:00
def get_person(self, person_id) :
2017-03-05 08:06:28 +03:00
person_server = self.lookup[person_id]
return person_server.people[person_id]
2021-03-14 13:08:05 +03:00
class PersonServer(object) :
2017-03-05 08:06:28 +03:00
2021-03-14 13:08:05 +03:00
def __init__(self) :
2017-03-05 08:06:28 +03:00
self.people = {} # key: person_id, value: person
2021-03-14 13:08:05 +03:00
def get_people(self, ids) :
2017-03-05 08:06:28 +03:00
results = []
for id in ids:
if id in self.people:
2021-03-14 13:08:05 +03:00
results.append(self.people[id])
2017-03-05 08:06:28 +03:00
return results
2021-03-14 13:08:05 +03:00
class UserGraphService(object) :
2017-03-05 08:06:28 +03:00
2021-03-14 13:08:05 +03:00
def __init__(self, person_ids, lookup) :
2017-03-05 08:06:28 +03:00
self.lookup = lookup
self.person_ids = person_ids
2021-03-14 13:08:05 +03:00
self.visited_ids = set()
2017-03-05 08:06:28 +03:00
2021-03-14 13:08:05 +03:00
def bfs(self, source, dest) :
2017-03-05 08:06:28 +03:00
# Use self.visited_ids to track visited nodes
# Use self.lookup to translate a person_id to a Person
pass