""" John Rachlin DS 2000: Intro to Programming with Data Filename: network.py Description: A simple social network """ class Network: def __init__(self): """ Constructor """ self.dict = {} # state variable "attribute" of Network def add_person(self, name): """ Adds a new person to the network """ if name not in self.dict: self.dict[name] = [] def friend(self, name1, name2): """ Make two people MUTUAL friends """ self.add_person(name1) self.add_person(name2) if name2 not in self.get_friends(name1): self.dict[name1].append(name2) if name1 not in self.get_friends(name2): self.dict[name2].append(name1) def get_friends(self, name): """ Return all the friends of as a list""" self.add_person(name) return self.dict[name] def recommend(self, name): """ Return friends of friends Exclude existing friends. Exclude name him/herself Dont recommend a person more than once """ recs = [] friends = self.get_friends(name) # immediate friends for friend in friends: friendsfriends = self.get_friends(friend) for f in friendsfriends: if f != name and f not in recs and f not in friends: recs.append(f) return recs def main(): net = Network() #net.add_person("John") #net.add_person("Laney") #print("Before: ", net.dict) net.friend("John", "Laney") net.friend("John", "Emma") net.friend("John", "Dachuan") net.friend("Laney", "Leilani") #print("After : ", net.dict) print("Friends of Leilani: ", net.get_friends("Leilani")) print("Recommendations : ", net.recommend("Leilani")) if __name__ == '__main__': main()