From 780e24a2066c93a593298c91fe8d72c43094347c Mon Sep 17 00:00:00 2001 From: Anda-Raluca Epure Date: Thu, 20 Oct 2022 10:56:17 +0100 Subject: [PATCH 1/4] Create friends' group --- group.py | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/group.py b/group.py index e2ec347..5aeef1e 100644 --- a/group.py +++ b/group.py @@ -1,5 +1,24 @@ """An example of how to represent a group of acquaintances in Python.""" -# Your code to go here... +my_group = [{"name":"Jill", + "job":"biologist", + "relationship":[("friend","Zalika"),("partner","John")], + "age":26}, + {"name":"Zalika", + "job":"artist", + "relationship":[("friend","Jill")], + "age":28}, + {"name":"John", + "job":"writer", + "relationship":[("partner","Jill")], + "age":27}, + {"name":"Nash", + "job":"chef", + "relationship":[("landlord","Zalika"),("cousin","John")], + "age":34} + ] + +#print(my_group[0]['name'] + " is " + str(my_group[0]["age"]) +", a " + my_group[0]["job"] +" and she is " + my_group[0]['relationship'][0][1] + "'s " + my_group[0]['relationship'][0][0]) + + -my_group = From 3e215e33ca818cc47ab470a7d2ee1abc40da680a Mon Sep 17 00:00:00 2001 From: Anda-Raluca Epure Date: Sun, 23 Oct 2022 13:07:45 +0100 Subject: [PATCH 2/4] Homework : print statements using list comprehensions for group of friends. --- group.py | 39 ++++++++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/group.py b/group.py index 5aeef1e..155baf8 100644 --- a/group.py +++ b/group.py @@ -1,24 +1,41 @@ """An example of how to represent a group of acquaintances in Python.""" -my_group = [{"name":"Jill", - "job":"biologist", - "relationship":[("friend","Zalika"),("partner","John")], - "age":26}, - {"name":"Zalika", - "job":"artist", - "relationship":[("friend","Jill")], - "age":28}, - {"name":"John", +my_group = [ + {"name":"Jill", + "job":"biologist", + "relationship":[("friend","Zalika"),("partner","John")], + "age":26} + , + {"name":"Zalika", + "job":"artist", + "relationship":[("friend","Jill")], + "age":28} + , + {"name":"John", "job":"writer", "relationship":[("partner","Jill")], "age":27}, - {"name":"Nash", + {"name":"Nash", "job":"chef", "relationship":[("landlord","Zalika"),("cousin","John")], "age":34} - ] + ] #print(my_group[0]['name'] + " is " + str(my_group[0]["age"]) +", a " + my_group[0]["job"] +" and she is " + my_group[0]['relationship'][0][1] + "'s " + my_group[0]['relationship'][0][0]) +#Homework - Anda +#The indices of the dictionnaries representing the data related to friends, for the my_group list. +list = [j for j in range(my_group.__len__())] +#maximum age of ppl in the group +[print(max(age)) for age in [[my_group[i]['age'] for i in list]]] + +#the average (mean) number of relations among members of the group +[print(total/my_group.__len__()) for total in [sum([my_group[i]['relationship'].__len__() for i in list])]] + +#the maximum age of people in the group that have at least one relation +[print(max(age)) for age in [[my_group[i]['age'] for i in list if my_group[i]['relationship'].__len__()>=1]]] + +#[more advanced] the maximum age of people in the group that have at least one friend +[print(max(age)) for age in [[my_group[i]['age'] for i in list if ('friend' in [my_group[i]['relationship'][j][0] for j in range(my_group[i]['relationship'].__len__())])]]] From ce9d45f15b08925a0a2ee231b77b742f46db176b Mon Sep 17 00:00:00 2001 From: Anda-Raluca Epure Date: Wed, 26 Oct 2022 22:21:56 +0100 Subject: [PATCH 3/4] Created a json file with the my_group information and tested with print statements. --- group.py | 27 ++++++++++++++++++++++++++ my_group.json | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 my_group.json diff --git a/group.py b/group.py index 155baf8..4a2dcfc 100644 --- a/group.py +++ b/group.py @@ -1,3 +1,6 @@ +from distutils.file_util import write_file +import json + """An example of how to represent a group of acquaintances in Python.""" my_group = [ @@ -39,3 +42,27 @@ #[more advanced] the maximum age of people in the group that have at least one friend [print(max(age)) for age in [[my_group[i]['age'] for i in list if ('friend' in [my_group[i]['relationship'][j][0] for j in range(my_group[i]['relationship'].__len__())])]]] + + + + +#USE OF JASON FILES +with open('my_group.json','w') as infile: + json.dump(my_group,infile,indent=4) + "Created the input file" +with open('my_group.json') as infile_test: + my_group_string = infile_test.read() + +#print(json.dumps(my_group)) +#print(json.dumps(my_group,indent=4)) +print(my_group_string) +print('\n') + +# Method can be used to parse a valid JSON string and convert it into a Python Dictionary. +my_group_test = json.loads(my_group_string) + +print(my_group_test[0]) +print('\n') +print(my_group[1]['job']) +print('\n') +print(my_group_test) diff --git a/my_group.json b/my_group.json new file mode 100644 index 0000000..52ce22d --- /dev/null +++ b/my_group.json @@ -0,0 +1,54 @@ +[ + { + "name": "Jill", + "job": "biologist", + "relationship": [ + [ + "friend", + "Zalika" + ], + [ + "partner", + "John" + ] + ], + "age": 26 + }, + { + "name": "Zalika", + "job": "artist", + "relationship": [ + [ + "friend", + "Jill" + ] + ], + "age": 28 + }, + { + "name": "John", + "job": "writer", + "relationship": [ + [ + "partner", + "Jill" + ] + ], + "age": 27 + }, + { + "name": "Nash", + "job": "chef", + "relationship": [ + [ + "landlord", + "Zalika" + ], + [ + "cousin", + "John" + ] + ], + "age": 34 + } +] \ No newline at end of file From 3ade32bf283aa0f0d5ceb78b1f82b23730dfe186 Mon Sep 17 00:00:00 2001 From: Anda Epure <115105750+anda-raluca@users.noreply.github.com> Date: Wed, 7 Dec 2022 22:34:05 +0000 Subject: [PATCH 4/4] Homework : print statements using list comprehensions for group of friends. --- README.md | 15 ------- refactoring/initial_global.py | 59 ++++++++++++++++++++++++++ refactoring/initial_person_class.py | 44 +++++++++++++++++++ refactoring/initial_two_classes.py | 66 +++++++++++++++++++++++++++++ 4 files changed, 169 insertions(+), 15 deletions(-) create mode 100644 refactoring/initial_global.py create mode 100644 refactoring/initial_person_class.py create mode 100644 refactoring/initial_two_classes.py diff --git a/README.md b/README.md index 6d7f0c9..e3e9a06 100644 --- a/README.md +++ b/README.md @@ -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?) diff --git a/refactoring/initial_global.py b/refactoring/initial_global.py new file mode 100644 index 0000000..988c810 --- /dev/null +++ b/refactoring/initial_global.py @@ -0,0 +1,59 @@ +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(person1, person2,group): + """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,group): + """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("Nash", 34, "chef", nash_relations,group) + forget("Nash", "John",group) + + 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!") diff --git a/refactoring/initial_person_class.py b/refactoring/initial_person_class.py new file mode 100644 index 0000000..569d26d --- /dev/null +++ b/refactoring/initial_person_class.py @@ -0,0 +1,44 @@ +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""" + pass + + +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") + + # ...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") + + # ... 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!") diff --git a/refactoring/initial_two_classes.py b/refactoring/initial_two_classes.py new file mode 100644 index 0000000..a54d1b3 --- /dev/null +++ b/refactoring/initial_two_classes.py @@ -0,0 +1,66 @@ +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.""" + pass + + 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""" + pass + + 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 + + def forget(self, name1, name2): + """Remove the connection between two people.""" + pass + + 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") + # ...then their connections + my_group.connect("Jill", "Zalika", "friend") + # ... then forget Nash and John's connection + my_group.forget("Nash", "John") + + 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!")