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

Refactoring - week09 #171

Open
wants to merge 5 commits into
base: week09
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
55 changes: 34 additions & 21 deletions week09/improvement/boids.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,39 +6,52 @@
This code simulates the swarming behaviour of bird-like objects ("boids").
"""

from matplotlib import pyplot as plt
from matplotlib import animation

import random
x_min = -450
x_max = 50
y_min = 300
y_max = 600
x_velocity_min = 0
x_velocity_max = 10
y_velocity_min = -20
y_velocity_max = 20

#picks a random number inside distribution with bounds (x_min, x_max)
boids_x = [random.uniform(x_min, x_max)]
boids_y = [random.uniform(y_min, y_max)]

boid_x_velocities = [random.uniform(x_velocity_min, x_velocity_max)]
boid_y_velocities = [random.uniform(y_velocity_min, y_velocity_max)]

boids = (boids_x, boids_y, boid_x_velocities, boid_y_velocities)

boids_x=[random.uniform(-450,50.0) for x in range(50)]
boids_y=[random.uniform(300.0,600.0) for x in range(50)]
boid_x_velocities=[random.uniform(0,10.0) for x in range(50)]
boid_y_velocities=[random.uniform(-20.0,20.0) for x in range(50)]
boids=(boids_x,boids_y,boid_x_velocities,boid_y_velocities)

def update_boids(boids):
xs,ys,xvs,yvs=boids
multiplier = 0.01
multiplier_velocity = 0.125
xs, ys, xvs, yvs = boids

# Fly towards the middle
for i in range(len(xs)):
for j in range(len(xs)):
xvs[i]=xvs[i]+(xs[j]-xs[i])*0.01/len(xs)
for i in range(len(xs)):
for j in range(len(xs)):
yvs[i]=yvs[i]+(ys[j]-ys[i])*0.01/len(xs)
xvs[i] = xvs[i] + (xs[j] - xs[i]) * multiplier / len(xs)
yvs[i] = yvs[i] + (ys[j] - ys[i]) * multiplier / len(xs)

# Fly away from nearby boids
for i in range(len(xs)):
for j in range(len(xs)):
if (xs[j]-xs[i])**2 + (ys[j]-ys[i])**2 < 100:
xvs[i]=xvs[i]+(xs[i]-xs[j])
yvs[i]=yvs[i]+(ys[i]-ys[j])
if (xs[j] - xs[i])**2 + (ys[j] - ys[i])**2 < 100:
xvs[i] = xvs[i] + (xs[i] - xs[j])
yvs[i] = yvs[i] +( ys[i] - ys[j])

# Try to match speed with nearby boids
for i in range(len(xs)):
for j in range(len(xs)):
if (xs[j]-xs[i])**2 + (ys[j]-ys[i])**2 < 10000:
xvs[i]=xvs[i]+(xvs[j]-xvs[i])*0.125/len(xs)
yvs[i]=yvs[i]+(yvs[j]-yvs[i])*0.125/len(xs)
if (xs[j] - xs[i])**2 + (ys[j] - ys[i])**2 < 10000:
xvs[i] = xvs[i] + (xvs[j] - xvs[i]) * multiplier_velocity / len(xs)
yvs[i] = yvs[i]+(yvs[j]-yvs[i]) * multiplier_velocity / len(xs)

# Move according to velocities
for i in range(len(xs)):
xs[i]=xs[i]+xvs[i]
ys[i]=ys[i]+yvs[i]
xs[i] = xs[i] + xvs[i]
ys[i] = ys[i] + yvs[i]
71 changes: 35 additions & 36 deletions week09/refactoring/initial_global.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
def average_age():
"""Compute the average age of the group's members."""
def average_age(group):
all_ages = [person["age"] for person in group.values()]
return sum(all_ages) / len(group)


def forget(person1, person2):
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(name, age, job, relations):
def add_person(group, name, age, job, relations):
"""Add a new person with the given characteristics to the group."""
new_person = {
"age": age,
Expand All @@ -20,42 +19,42 @@ def add_person(name, age, job, relations):
group[name] = new_person


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"
}
if __name__ == "__main__":

add_person("Nash", 34, "chef", nash_relations)
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"
}
}
}

forget("Nash", "John")
nash_relations = {
"John": "cousin",
"Zalika": "landlord"
}

if __name__ == "__main__":
add_person(group, "Nash", 34, "chef", nash_relations)
forget(group, "Nash", "John")
assert len(group) == 4, "Group should have 4 members"
assert average_age() == 28.75, "Average age of the group is incorrect!"
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!")
15 changes: 14 additions & 1 deletion week09/refactoring/initial_person_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ def add_connection(self, person, relation):

def forget(self, person):
"""Removes any connections to a person"""
pass
if person not in self.connections:
raise ValueError(f"I don't know anything about {person.name}")
self.connections.pop(person, None)
person.connections.pop(self, None)


def average_age(group):
Expand All @@ -28,10 +31,20 @@ def average_age(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")
zalika.add_connection(nash, "landlord")
john.add_connection(jill, "partner")
john.add_connection(nash, "cousin")
nash.add_connection(zalika, "landlord")
nash.add_connection(john, "cousin")

# ... then forget Nash and John's connection
nash.forget(john)
Expand Down
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