Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring: Remove global variables #76

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 0 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,3 @@ acquaintances using dictionaries and lists.
- Each person in the group has an age.
- Each person in the group can have a job.
- Each person can be connected to others in different ways, such as "friend", "granddaughter", "colleague" etc.

Think about how you want to represent the various types of information and the connections between them.

# Part 1
Create an example instance, in an editor or a notebook, of a structure for this group:
- Jill is 26, a biologist and she is Zalika's friend and John's partner.
- Zalika is 28, an artist, and Jill's friend
- John is 27, a writer, and Jill's partner.
- Nash is 34, a chef, John's cousin and Zalika's landlord.

Some things you may wish to consider in your model:
- Does it allow people who have no job?
- Does it allow people with no connections?
- Does it assume that connections are always reciprocal (e.g. if A is B's friend, does B
automatically consider A a friend too?)
5 changes: 0 additions & 5 deletions group.py

This file was deleted.

60 changes: 60 additions & 0 deletions refactoring/initial_global.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
def average_age(group):
"""Compute the average age of the group's members."""
all_ages = [person["age"] for person in group.values()]
return sum(all_ages) / len(group)


def forget(group, person1, person2):
"""Remove the connection between two people."""
group[person1]["relations"].pop(person2, None)
group[person2]["relations"].pop(person1, None)


def add_person(group, name, age, job, relations):
"""Add a new person with the given characteristics to the group."""
new_person = {
"age": age,
"job": job,
"relations": relations
}
group[name] = new_person

if __name__ == "__main__":
group = {
"Jill": {
"age": 26,
"job": "biologist",
"relations": {
"Zalika": "friend",
"John": "partner"
}
},
"Zalika": {
"age": 28,
"job": "artist",
"relations": {
"Jill": "friend",
}
},
"John": {
"age": 27,
"job": "writer",
"relations": {
"Jill": "partner"
}
}
}

nash_relations = {
"John": "cousin",
"Zalika": "landlord"
}

add_person(group, "Nash", 34, "chef", nash_relations)

forget(group, "Nash", "John")

assert len(group) == 4, "Group should have 4 members"
assert average_age(group) == 28.75, "Average age of the group is incorrect!"
assert len(group["Nash"]["relations"]) == 1, "Nash should only have one relation"
print("All assertions have passed!")
52 changes: 52 additions & 0 deletions refactoring/initial_person_class.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
class Person:
"""A class to represent an individual and their connections."""

def __init__(self, name, age, job):
"""Create a new Person with the given name, age and job and no connections."""
self.name = name
self.age = age
self.job = job
self.connections = dict()

def add_connection(self, person, relation):
"""Add a new connection to a person"""
if person in self.connections:
raise ValueError(f"I already know about {person.name}")
self.connections[person] = relation

def forget(self, person):
"""Removes any connections to a person"""
self.connections.pop(person, None)


def average_age(group):
"""Compute the average age of the group's members."""
all_ages = [person.age for person in group]
return sum(all_ages) / len(group)


if __name__ == "__main__":
# ...then create the group members one by one...
jill = Person("Jill", 26, "biologist")
zalika = Person("Zalika", 28, "artist")
john = Person("John", 27, "writer")
nash = Person("Nash", 34, "chef")

# ...then add the connections one by one...
# Note: this will fail from here if the person objects aren't created
jill.add_connection(zalika, "friend")
jill.add_connection(john, "partner")
zalika.add_connection(jill, "friend")
john.add_connection(jill, "partner")
nash.add_connection(john, "cousin")
nash.add_connection(zalika, "landlord")

# ... then forget Nash and John's connection
nash.forget(john)
# Then create the group
my_group = {jill, zalika, john, nash}

assert len(my_group) == 4, "Group should have 4 members"
assert average_age(my_group) == 28.75, "Average age of the group is incorrect!"
assert len(nash.connections) == 1, "Nash should only have one relation "
print("All assertions have passed!")
85 changes: 85 additions & 0 deletions refactoring/initial_two_classes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
class Person:
"""A class to represent an individual."""

def __init__(self, name, age, job):
"""Create a new Person with the given name, age and job."""
self.name = name
self.age = age
self.job = job


class Group:
"""A class that represents a group of individuals and their connections."""

def __init__(self):
"""Create an empty group."""
self.members = []
self.connections = {}

def size(self):
"""Return how many people are in the group."""
return len(self.members)

def contains(self, name):
"""Check whether the group contains a person with the given name.
Useful to throw errors if we try to add a person who already exists or forget someone.
"""
return any(member.name == name for member in self.members)

def add_person(self, name, age, job):
"""Add a new person with the given characteristics to the group."""
self.members.append(Person(name, age, job))

def number_of_connections(self, name):
"""Find the number of connections that a person in the group has"""
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
"""
if name1 not in self.connections:
self.connections[name1] = []
if name2 not in self.connections:
self.connections[name2] = []

self.connections[name1].append({name2: relation})

if reciprocal:
self.connections[name2].append({name1: relation})

def forget(self, name1, name2):
"""Remove the connection between two people."""
if name1 in self.connections:
self.connections[name1] = [conn for conn in self.connections[name1] if name2 not in conn]
if name2 in self.connections:
self.connections[name2] = [conn for conn in self.connections[name2] if name1 not in conn]

def average_age(self):
"""Compute the average age of the group's members."""
all_ages = [person.age for person in self.members]
return sum(all_ages) / self.size()


if __name__ == "__main__":
# Start with an empty group...
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", "John", "partner")
my_group.connect("Nash", "John", "cousin")
my_group.connect("Nash", "Zalika", "landlord", reciprocal=False)
# ... then forget Nash and John's connection
my_group.forget("Nash", "John")

assert my_group.contains("John"), "John should be in the group"
assert my_group.size() == 4, "Group should have 4 members"
assert my_group.average_age() == 28.75, "Average age of the group is incorrect!"
assert my_group.number_of_connections("Nash") == 1, "Nash should only have one relation"
print("All assertions have passed!")