Chapter 1

Playing around with stuff from chapter 1 in "Data Science from Scratch"

"Shannon" in class on Jan 24 2020

In [5]:
from scratch.introduction import users, friendship_pairs
In [6]:
users
Out[6]:
[{'id': 0, 'name': 'Hero'},
 {'id': 1, 'name': 'Dunn'},
 {'id': 2, 'name': 'Sue'},
 {'id': 3, 'name': 'Chi'},
 {'id': 4, 'name': 'Thor'},
 {'id': 5, 'name': 'Clive'},
 {'id': 6, 'name': 'Hicks'},
 {'id': 7, 'name': 'Devin'},
 {'id': 8, 'name': 'Kate'},
 {'id': 9, 'name': 'Klein'}]
In [7]:
friendship_pairs
Out[7]:
[(0, 1),
 (0, 2),
 (1, 2),
 (1, 3),
 (2, 3),
 (3, 4),
 (4, 5),
 (5, 6),
 (5, 7),
 (6, 8),
 (7, 8),
 (8, 9)]

What is the average number of friends that any given user has?

In [9]:
# Add a 'friends' field to the user list
for user in users:
    user['friends'] = []
users
Out[9]:
[{'id': 0, 'name': 'Hero', 'friends': []},
 {'id': 1, 'name': 'Dunn', 'friends': []},
 {'id': 2, 'name': 'Sue', 'friends': []},
 {'id': 3, 'name': 'Chi', 'friends': []},
 {'id': 4, 'name': 'Thor', 'friends': []},
 {'id': 5, 'name': 'Clive', 'friends': []},
 {'id': 6, 'name': 'Hicks', 'friends': []},
 {'id': 7, 'name': 'Devin', 'friends': []},
 {'id': 8, 'name': 'Kate', 'friends': []},
 {'id': 9, 'name': 'Klein', 'friends': []}]
In [10]:
for (user1, user2) in friendship_pairs:
    users[user1]['friends'].append(user2)
    users[user2]['friends'].append(user1)
users
Out[10]:
[{'id': 0, 'name': 'Hero', 'friends': [1, 2]},
 {'id': 1, 'name': 'Dunn', 'friends': [0, 2, 3]},
 {'id': 2, 'name': 'Sue', 'friends': [0, 1, 3]},
 {'id': 3, 'name': 'Chi', 'friends': [1, 2, 4]},
 {'id': 4, 'name': 'Thor', 'friends': [3, 5]},
 {'id': 5, 'name': 'Clive', 'friends': [4, 6, 7]},
 {'id': 6, 'name': 'Hicks', 'friends': [5, 8]},
 {'id': 7, 'name': 'Devin', 'friends': [5, 8]},
 {'id': 8, 'name': 'Kate', 'friends': [6, 7, 9]},
 {'id': 9, 'name': 'Klein', 'friends': [8]}]
In [15]:
for user in users:
    user['friend_count'] = len(user['friends'])
users
Out[15]:
[{'id': 0, 'name': 'Hero', 'friends': [1, 2], 'friend_count': 2},
 {'id': 1, 'name': 'Dunn', 'friends': [0, 2, 3], 'friend_count': 3},
 {'id': 2, 'name': 'Sue', 'friends': [0, 1, 3], 'friend_count': 3},
 {'id': 3, 'name': 'Chi', 'friends': [1, 2, 4], 'friend_count': 3},
 {'id': 4, 'name': 'Thor', 'friends': [3, 5], 'friend_count': 2},
 {'id': 5, 'name': 'Clive', 'friends': [4, 6, 7], 'friend_count': 3},
 {'id': 6, 'name': 'Hicks', 'friends': [5, 8], 'friend_count': 2},
 {'id': 7, 'name': 'Devin', 'friends': [5, 8], 'friend_count': 2},
 {'id': 8, 'name': 'Kate', 'friends': [6, 7, 9], 'friend_count': 3},
 {'id': 9, 'name': 'Klein', 'friends': [8], 'friend_count': 1}]
In [16]:
total = 0
for user in users:
    total += user['friend_count']
average_friends = total / len(users)
average_friends
Out[16]:
2.4
In [ ]: