Last active
October 29, 2021 08:15
-
-
Save stefpiatek/f23f8b4e65066d17319cc3a651e0a198 to your computer and use it in GitHub Desktop.
Example solution: Friend group data functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| 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" | |
| } | |
| } | |
| } | |
| if __name__ == "__main__": | |
| # test out functions | |
| # add person | |
| nash_relations = { | |
| "John": "cousin", | |
| "Zalika": "landlord" | |
| } | |
| add_person(group, "Nash", 34, "chef", nash_relations) | |
| assert len(group) == 4, "Group should have 4 members" | |
| # average age | |
| assert average_age(group) == 28.75, "Average age of the group is incorrect!" | |
| # forget | |
| forget(group, "Nash", "John") | |
| assert len(group["Nash"]["relations"]) == 1, "Nash should only have one relation" | |
| print("All assertions have passed!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment