Skip to content
This repository has been archived by the owner on Oct 25, 2024. It is now read-only.

Commit

Permalink
split fucntionality in two classes (Person, Group)
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikolaos Schoinas committed Dec 9, 2020
1 parent b1690b0 commit f06bfb4
Showing 1 changed file with 39 additions and 5 deletions.
44 changes: 39 additions & 5 deletions week09/refactoring/initial_two_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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."""
Expand All @@ -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!"
Expand Down

0 comments on commit f06bfb4

Please sign in to comment.