|
1 | 1 | """An example of how to represent a group of acquaintances in Python.""" |
2 | 2 |
|
3 | | -# Your code to go here... |
| 3 | +# Define the group as a series of nested dictionaries |
4 | 4 |
|
5 | 5 | my_group = {'Jill' : |
6 | 6 | {'age' : 26 , 'job' : 'biologist' , 'connections' : |
|
15 | 15 | {'age' : 34 , 'job' : 'chef' , 'connections' : |
16 | 16 | {'cousin' : 'John' , 'tenant' : 'Zalika'} } } |
17 | 17 |
|
| 18 | + |
| 19 | + |
| 20 | +# Simple loop to extract ages from the group, and choose the largest |
| 21 | + |
| 22 | +max_age = 0 |
| 23 | + |
| 24 | +for a in my_group: |
| 25 | + age = my_group[a]['age'] |
| 26 | + if age > max_age: |
| 27 | + max_age = age |
| 28 | + |
| 29 | +print("The oldest person in the group is",max_age,"years old.") |
| 30 | + |
| 31 | + |
| 32 | +# Find the mean number of relations in the group |
| 33 | + |
| 34 | +num_relations = [] |
| 35 | + |
| 36 | +for a in my_group: |
| 37 | + relations = my_group[a]['connections'] |
| 38 | + num_relations.append(len(relations)) |
| 39 | + |
| 40 | +import statistics |
| 41 | +mean_number = statistics.mean(num_relations) |
| 42 | + |
| 43 | +print("The mean number of relations amongst the group is",mean_number,"relations.") |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | +# Find the maximum age of people with 1+ relations |
| 48 | + |
| 49 | +max_age2 = 0 |
| 50 | + |
| 51 | +for a in my_group: |
| 52 | + num_relations2 = len(my_group[a]['connections']) |
| 53 | + if num_relations2 >= 1: |
| 54 | + age2 = my_group[a]['age'] |
| 55 | + if age2 > max_age2: |
| 56 | + max_age2 = age2 |
| 57 | + |
| 58 | +print("The oldest person in the group with at least 1 relation is",max_age2,"years old.") |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | +# Find the maximum age of people with 1+ friends |
| 63 | + |
| 64 | +max_age3 = 0 |
| 65 | + |
| 66 | +for a in my_group: |
| 67 | + connections = my_group[a]['connections'] |
| 68 | + if "friend" in connections: |
| 69 | + friends = connections['friend'] |
| 70 | + if isinstance(friends, dict): |
| 71 | + num_friends = len(friends) |
| 72 | + elif isinstance(friends, str): |
| 73 | + num_friends = 1 |
| 74 | + if num_friends >= 1: |
| 75 | + age3 = my_group[a]['age'] |
| 76 | + if age3 > max_age3: |
| 77 | + max_age3 = age3 |
| 78 | + |
| 79 | +print("The oldest person in the group with at least 1 friend is",max_age3,"years old.") |
0 commit comments