Question:
I have many python lists of varying length, all containing only integers.
How can I find the 2 lists that have the most elements in common?
example input:
list1 = [234, 982, 908, 207, 456, 284, 473]
list2 = [845, 345, 765, 678]
list3 = [120, 542, 764, 908, 217, 778, 999, 326, 456]
# thousands more lists ...
example output:
# 2 most similar lists:
list400, list6734
Note: I am NOT looking to find the most common elements across the lists, only which 2 lists are the most similar i.e. have the most elements in common. I am also not concerned with the similarity of individual elements. An element is either found within 2 lists, or it isn't.
Context:
I have a data set representing which users have liked certain posts on a platform. If 2 users both like the same post, they have a common_like_score of 1. if 2 users like 10 of the same posts, they have a common like score of 10. My goal is to find the 2 users with the highest common_like_score
I have loaded the data (from CSV) into a pandas data frame, each row represents a like between the user and the post:
| index | user id | post id |
|---|---|---|
| 0 | 201 | 234 |
| 1 | 892 | 908 |
| 2 | 300 | 825 |
etc. thousands more rows.
My approach has been to group the data by user id and then concat the posts for each user into a single row / column as a comma separated string:
df = df[df['user id'].duplicated(keep=False)]
df['post id'] = df['post id'].astype(str)
df['liked posts'] = df.groupby('user id')['post id'].transform(lambda x: ','.join(x))
df = df.drop(columns=['post id'])
df = df[['user id', 'liked posts']].drop_duplicates()
The resulting dataframe:
| index | user id | liked posts |
|---|---|---|
| 0 | 201 | 234,789,267, ... |
| 1 | 892 | 908,734,123, ... |
| 2 | 300 | 825,456,765, ... |
etc. where user id is a unique row ...
Hence my question - I need to find which rows of the data frame have the most numbers in common in the liked posts column, to return the 2 users with the highest common_like_score.
If there is a better solution to the overall problem, please also share it.