Project 2
Project 2
{'id':0,'name':'Ashok'},
{'id':1, 'name':'Rahul'},
{'id':2, 'name':'Sarita'},
{'id':3, 'name':'Rohan'},
{'id':4, 'name':'Akhaya'},
{'id':5, 'name':'Prakash'},
{'id':6, 'name':'Madhabi'},
{'id':7, 'name':'Spandan'}
interests=[(0,'python'),(0,'java'),(1,'java'),(2,'python'),(2,'java'),(3,'python'),
(4,'c'),(5,'c'),
(6,'python'),(7,'java')]
'''
target_interest: The interest to search for.
user_interests: A list of tuples where each tuple contains a user ID and their
interest.
It returns a list comprehension that filters user_interests based on
whether the target_interest matches the interest of the user in each tuple,
returning a list of user IDs who have the specified interest.
'''
def data_scientists_who_like(target_interest, user_interests):
return [
user_id
for user_id, user_interest in user_interests
if user_interest == target_interest
]
'''
Users interested in 'python': [0, 2, 3, 6]
Users interested in 'java': [0, 1, 2, 7]
Users interested in 'java': [0, 1, 2, 7]
Users interested in 'python': [0, 2, 3, 6]
Users interested in 'java': [0, 1, 2, 7]
Users interested in 'python': [0, 2, 3, 6]
Users interested in 'c': [4, 5]
Users interested in 'c': [4, 5]
Users interested in 'python': [0, 2, 3, 6]
Users interested in 'java': [0, 1, 2, 7]
'''
'''
defaultdict(<class 'list'>, {'python': [0, 2, 3, 6], 'java': [0, 1, 2, 7], 'c': [4,
5]})
'''
'''
Efficiency:
Code 2 iterates through the interests list only once to populate the
user_ids_by_interest dictionary.
In contrast, Code 1 requires iterating through the interests list once for each
target interest
when calling the data_scientists_who_like() function within the loop.
This could lead to redundant iterations, especially if there are many interests.
Data Organization:
'''
# # Keys are user_ids, values are lists of interests for that user_id.
interests_by_user_id = defaultdict(list)
for user_id, interest in interests:
interests_by_user_id[user_id].append(interest)
print(interests_by_user_id)
'''
defaultdict(<class 'list'>, {0: ['python', 'java'], 1: ['java'], 2: ['python',
'java'],
3: ['python'], 4: ['c'], 5: ['c'], 6: ['python'], 7:
['java']})
'''