Group unique users with two changing IDs

Viewed 223

Can you think of a faster algorithm for this problem? Or improve the code?

Problem:

I have two customer IDs:

  • ID1 (e.g. phone number)
  • ID2 (e.g. email address)

A user sometimes change their ID1 and sometimes ID2. How can I find unique users?

Example:

ID1 = [7, 7, 8, 9]

ID2 = [a, b, b, c]

Desired result:

ID3 = [Anna, Anna, Anna, Paul]

enter image description here

The real world scenario has ca. 600 000 items per list.

There is already an SQL idea here: How can I match Employee IDs from 2 columns and group them into an array?

And I got help from a friend which had this idea with TypeScript: https://stackblitz.com/edit/typescript-leet-rewkmh?file=index.ts

A second friend of mine helped me with some pseudo-code, and I was able to create this:

Fastest (not working anymore) code so far:

ID1 = [7, 7, 8, 9]
ID2 = ["a", "b", "b", "c"]

def timeit_function(ID1, ID2):
    
    def find_user_addresses():
        phone_i = []
        email_i = []
        
        tmp1 = [ID1[0]]
        tmp2 = []
        tmp_index = []

        while len(tmp1) != 0 or len(tmp2) != 0:
            while len(tmp1) != 0:
                tmp_index = []  
                for index, value in enumerate(ID1):
                    if value == tmp1[0]:
                        tmp2.append(ID2[index])
                        tmp_index.insert(-1, index)

                for i in tmp_index: 
                    del ID1[i]
                    del ID2[i]
                tmp1 = list(dict.fromkeys(tmp1))
                phone_i.append(tmp1.pop(0))

            while len(tmp2) != 0:
                tmp_index = [] 
                for index, value in enumerate(ID2):
                    if value == tmp2[0]:
                        tmp1.append(ID1[index])
                        tmp_index.insert(0, index)

                for i in tmp_index: 
                    del ID1[i]
                    del ID2[i]
                tmp2 = list(dict.fromkeys(tmp2))
                email_i.append(tmp2.pop(0))

        return phone_i, email_i
    
    users = {}
    i = 0
    while len(ID1) != 0:
        phone_i, email_i = find_user_addresses()
        users[i] = [phone_i, email_i]
        i += 1
    return users

Output:

{0: [[7, 8], ['a', 'b']], 1: [[9], ['c']]}

Meaning: {User_0: [[phone1, phone2], [email1, email2]], User_1: [phone3, email3]}

Ranking

rank Username %timeit Unique users Correct output?
1. Zachary Vance 32 ms ± 1.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) 1408 yes
2. igrinis 5.54 s ± 81.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 1408 yes
(3.) dkapitan 8 s ± 106 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 3606 no
(4.) thenarfer 2.34 µs ± 3.25 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) 1494 no

The code was run with the two lists here (takes some time to load).

3 Answers

The idea is very simple:

  • for each entry
    • scan all existing users,

      • if any dimension of the entry matches previous user, extend his attribute set, and add him to the merge list
    • if was not matched to anyone existing create a new user,

    • otherwise group distinct users together

This should be pretty fast, as it scans the list only once and does not require recursion.

ID1 = [7, 7, 8, 9]
ID2 = ["a", "b", "b", "c"]
user = {}
new_user_idx = 0
for i in range(len(ID1)):
    merge = []   # this is a list of users that should be merged
    for k in user:
        # find if any feature is already found in previous user  
        if ID1[i] in user[k][0]:
            user[k][1].add(ID2[i])
            merge.append(k)
        if ID2[i] in user[k][1]:
            user[k][0].add(ID1[i])
            merge.append(k)
    if not merge:
        # we have to create a new user
        user[new_user_idx] = (set([ID1[i]]), set([ID2[i]]))
        new_user_idx += 1
    elif len(merge)>1:
        # merging existing users
        for el in set(merge[1:]):
            if el==merge[0]: continue  # skip unnecessary merge
            user[merge[0]][0].update(user[el][0]) # copy attributes
            user[merge[0]][1].update(user[el][1])
            user.pop(el) # delete merged user
print(user)   


{0: ({7, 8}, {'a', 'b'}), 1: ({9}, {'c'})}
 

Trying it with sets:

%%timeit
ID1 = [7, 7, 8, 9]
ID2 = ["a", "b", "b", "c"]

users = {0: {'phone': set([ID1[0]]), 'email': set([ID2[0]])}}

for index, id1 in enumerate(ID1):
    id2 = ID2[index]
    
    # iterate over found list of users
    i = 0
    n_users = max(users.keys()) 
    while i <= n_users:
        if any([(id1 in users[i]['phone']), (id2 in users[i]['email'])]):
            users[i]['phone'].add(id1)
            users[i]['email'].add(id2)
            break
        i += 1

    # add new user if not found
    if i > n_users:
        users[i] = {'phone': set([id1]), 'email': set([id2])}

Don't run timeit with a 5-element list. This is not a valid method to evaluate the contenders. Use bigger lists (1000+) to test performance, or you will not actually end up with the fast program you want.

I'll throw my hat in the ring, with an O(N) worst-case algorithm (doesn't depend on the number of users).

I'll point out the performance of the other algorithms depends a lot on the number of IDs a typical user has. This one is specialized to work well for a large number of IDs per user.

ID1 = [7, 7, 8, 9]
ID2 = ["a", "b", "b", "c"]

from collections import defaultdict

id1_to_id2 = defaultdict(set)
id2_to_id1 = defaultdict(set)
for id1, id2 in zip(ID1, ID2):
    id1_to_id2[id1].add(id2)
    id2_to_id1[id2].add(id1)

id1_to_user = {}
users = {}
for id1 in id1_to_id2:
    if id1 in id1_to_user:
        continue # Already processed

    # Find all id1 and id2 for this user, using 'floodfill'
    id1s = {id1}
    id2s = set()
    id1_queue = [id1]
    while len(id1_queue) > 0:
        old_id2s = id2s.copy()
        for id1 in id1_queue:
            id2s.update(id1_to_id2[id1]) # try using id2_queue = set().union(id1_to_id2[id1] for id1 in id1_queue)-id2s; id2s |= id2_queue as well in case it's faster
        id2_queue = id2s - old_id2s
        id1_queue = []
        old_id1s = id1s.copy()
        for id2 in id2_queue:
            id1s.update(id2_to_id1[id2])
        id2_queue = []
        id1_queue = id1s - old_id1s
    user = len(users)
    users[user] = [id1s, id2s]
    for id1 in id1s:
        id1_to_user[id1] = user

print(users)
Related