diff --git a/projects/social/social.py b/projects/social/social.py index 8609d8800..d1464907b 100644 --- a/projects/social/social.py +++ b/projects/social/social.py @@ -1,7 +1,29 @@ +import string +import random + + +class Queue: + def __init__(self): + self.storage = [] + + def enqueue(self, value): + self.storage.append(value) + + def dequeue(self): + if self.size() > 0: + return self.storage.pop(0) + else: + return None + + def size(self): + return len(self.storage) + + class User: def __init__(self, name): self.name = name + class SocialGraph: def __init__(self): self.last_id = 0 @@ -45,8 +67,22 @@ def populate_graph(self, num_users, avg_friendships): # !!!! IMPLEMENT ME # Add users + for i in range(num_users): + self.add_user((f"User {i+1}")) # Create friendships + possible_friendships = [] + for user_id in self.users: + for friend_id in range(user_id + 1, self.last_id + 1): + possible_friendships.append((user_id, friend_id)) + + random.shuffle(possible_friendships) + + for i in range(num_users * avg_friendships // 2): + friendship = possible_friendships[i] + user_id = friendship[0] + friend_id = friendship[1] + self.add_friendship(user_id, friend_id) def get_all_social_paths(self, user_id): """ @@ -59,6 +95,32 @@ def get_all_social_paths(self, user_id): """ visited = {} # Note that this is a dictionary, not a set # !!!! IMPLEMENT ME + # create an empty queue + # enqueue the first path. + # while the q is not empty. + # dequeue the path. + # set a newuser_id to the last element in the path [-1] + # if the newuser_id is not in visited. + # set the visited at the key of newuser_id to the path. + # for every friend_id in the friendships at the key of newuser_id + # make a copy of the path called new_path. + # append the friend_id to the new_path. + # enqueue the new path. + # return the populated visited dict to the caller + q = Queue() + q.enqueue([user_id]) + + while q.size() > 0: + path = q.dequeue() + + newuser_id = path[-1] + if newuser_id not in visited: + visited[newuser_id] = path + + for friend_id in self.friendships[newuser_id]: + new_path = path.copy() + new_path.append(friend_id) + q.enqueue(new_path) return visited