From f06bfb4e527adeaf89e2b629e892de45c0eea3ac Mon Sep 17 00:00:00 2001 From: Nikolaos Schoinas Date: Wed, 9 Dec 2020 19:00:00 +0000 Subject: [PATCH] split fucntionality in two classes (Person, Group) --- week09/refactoring/initial_two_classes.py | 44 ++++++++++++++++++++--- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/week09/refactoring/initial_two_classes.py b/week09/refactoring/initial_two_classes.py index a54d1b3..d561937 100644 --- a/week09/refactoring/initial_two_classes.py +++ b/week09/refactoring/initial_two_classes.py @@ -18,7 +18,7 @@ def __init__(self): def size(self): """Return how many people are in the group.""" - pass + return len(self.members) def contains(self, name): """Check whether the group contains a person with the given name. @@ -32,17 +32,42 @@ def add_person(self, name, age, job): def number_of_connections(self, name): """Find the number of connections that a person in the group has""" - pass + if not self.contains(name): + raise ValueError(f"I don't know anything about {name}") + + return len(self.connections[name]) def connect(self, name1, name2, relation, reciprocal=True): """Connect two given people in a particular way. Optional reciprocal: If true, will add the relationship from name2 to name 1 as well """ - pass + # connections dictionary has the form below: + """ connections = { + name1 : { + name2 : { + "relation" : relation + } + name3 : { + "relation" : relation + } + } + } """ + + if name1 not in self.connections: + self.connections[name1] = {} + self.connections[name1][name2] = {} + self.connections[name1][name2] = {"relation" : relation} + + if reciprocal: + if name2 not in self.connections: + self.connections[name2] = {} + self.connections[name2][name1] = {} + self.connections[name2][name1] = {"relation" : relation} + def forget(self, name1, name2): """Remove the connection between two people.""" - pass + self.connections[name1].pop(name2, None) def average_age(self): """Compute the average age of the group's members.""" @@ -55,10 +80,19 @@ def average_age(self): my_group = Group() # ...then add the group members one by one... my_group.add_person("Jill", 26, "biologist") + my_group.add_person("Zalika", 28, "artist") + my_group.add_person("John", 27, "writer") + my_group.add_person("Nash", 34, "chef") + # ...then their connections - my_group.connect("Jill", "Zalika", "friend") + my_group.connect("Jill", "Zalika", "friend", True) + my_group.connect("Jill", "John", "partner", True) + my_group.connect("Nash", "John", "cousin", True) + my_group.connect("Nash", "Zalika", "landlord", True) + # ... then forget Nash and John's connection my_group.forget("Nash", "John") + my_group.forget("John", "Nash") assert my_group.size() == 4, "Group should have 4 members" assert my_group.average_age() == 28.75, "Average age of the group is incorrect!"