Combine a list of pairs (tuples)?
<p>From a list of linked pairs, I want to combine the pairs into groups of common IDs, so that I can then write group_ids back to the database, eg:</p>

<pre><code>UPDATE table SET group = n WHERE id IN (...........);
</code></pre>

<p>Example:</p>

<pre><code>[(1,2), (3, 4), (1, 5), (6, 3), (7, 8)]
</code></pre>

<p>becomes</p>

<pre><code>[[1, 2, 5], [3, 4, 6], [7, 8]]
</code></pre>

<p>Which allows:</p>

<pre><code>UPDATE table SET group = 1 WHERE id IN (1, 2, 5);
UPDATE table SET group = 2 WHERE id IN (3, 4, 6);
UPDATE table SET group = 3 WHERE id IN (7, 8);
</code></pre>

<p>and</p>

<pre><code>[(1,2), (3, 4), (1, 5), (6, 3), (7, 8), (5, 3)]
</code></pre>

<p>becomes</p>

<pre><code>[[1, 2, 5, 3, 4, 6], [7, 8]]
</code></pre>

<p>Which allows:</p>

<pre><code>UPDATE table SET group = 1 WHERE id IN (1, 2, 5, 3, 4, 6);
UPDATE table SET group = 2 WHERE id IN (7, 8);
</code></pre>

<p>I have written some code which works. I pass in a list of tuples, where each tuple is a pair of linked ids.  I return a list of lists, where each internal list is a list of common id's.</p>

<p>I iterate over the list of tuples and assign each tuple element to groups as follows:</p>

<ul>
<li>if neither a nor b is in a list, create a new list, appened a and b and append the new list to the list of lists</li>
<li>if a is in a group but b isn't, add b to the a group</li>
<li>if b is in a group but a isn't, add a to the b group</li>
<li>if a and b are already in separate groups merge the a and b groups</li>
<li>if a and b are already in the same group, do nothing</li>
</ul>

<p>I am expecting millions of linked pairs, and I am expecting hundreds of thousand of gropus and hunderds of thousands of group members.   So, I need the algorithm to be fast, I am looking for some suggestions for some really efficient code.  Although I have implemented this to build a list of lists, I am open to anything, they key thing is being able to build the above SQL to get the group ids back to the database.</p>

<pre><code>def group_pairs(list_of_pairs):
    """

    :param list_of_pairs:
    :return:
    """
    groups = list()
    for pair in list_of_pairs:
        a_group = None
        b_group = None

        for group in groups:
            # find what group if any a and b belong to

            # don't bother checking if a group already found
            if a_group is None and pair[0] in group:
                a_group = group
            # don't bother checking if b group already found
            if b_group is None and pair[1] in group:
                b_group = group
            # if a and b found, stop looking
            if a_group is not None and b_group is not None:
                break

        if a_group is None:
            if b_group is None:
                # neither a nor b are in a group; create a new group and
                # add a and b
                groups.append([pair[0], pair[1]])
            else:
                # b is in a group but a isn't, so add a to the b group
                b_group.append(pair[0])
        elif a_group != b_group:
            if b_group is None:
                # a is in a group but b isn't, so add b to the a group
                a_group.append(pair[1])
            else:
                # a and b are in different groups, add join b to a and get
                # rid of b
                a_group.extend(b_group)
                groups.remove(b_group)
        elif a_group == b_group:
            # a and b already in same group, so nothing to do
            pass

    return groups
</code></pre>

<p>With:</p>

<pre><code>def make_equiv_classes(pairs):
    groups = {}
    for (x, y) in pairs:
        xset = groups.get(x, set([x]))
        yset = groups.get(y, set([y]))
        jset = xset | yset
        for z in jset:
            groups[z] = jset
    return set(map(tuple, groups.values()))
</code></pre>

<p>you can get:</p>

<pre><code>&gt;&gt;&gt; make_equiv_classes([(1,2), (3, 4), (1, 5), (6, 3), (7, 8)])
{(1, 2, 5), (3, 4, 6), (8, 7)}

&gt;&gt;&gt; make_equiv_classes([(1,2), (3, 4), (1, 5), (6, 3), (7, 8), (5, 3)])
{(1, 2, 3, 4, 5, 6), (8, 7)}
</code></pre>

<p>The complexity should be <em>O(np)</em>, where <em>n</em> is the number of distinct integer values, and <em>p</em> is the number of pairs.</p>

<p>I think <code>set</code> is the proper type for a single group, because it makes the union operation fast and easy to express, and <code>dict</code> is the right way to store <code>groups</code> because you get constant-time lookup for asking the question of what group a particular integer value belongs to.</p>

<p>We can set up a test harness to time this code, if we want to.  To start, we can build a random graph over something moderately large, like 10K nodes (i.e., distinct integer values).  I'll put in 5K random links (pairs), since that tends to give me thousands of groups, which together account for about two thirds of the nodes (that is, about 3K nodes will be in a singleton groups, not linked to anything else).</p>

<pre><code>import random
pairs = []
while len(pairs) &lt; 5000:
    a = random.randint(1,10000)
    b = random.randint(1,10000)
    if a != b:
        pairs.append((a,b))
</code></pre>

<p>Then, we can just time this (I'm using IPython magic here):</p>

<pre><code>In [48]: %timeit c = make_equiv_classes(pairs)
10 loops, best of 3: 63 ms per loop
</code></pre>

<p>which is faster than your initial solution:</p>

<pre><code>In [49]: %timeit c = group_pairs(pairs)
1 loop, best of 3: 2.08 s per loop
</code></pre>

<p>We can also use this random graph to check that the output of the two functions is identical for some large random input:</p>

<pre><code>&gt;&gt;&gt; c = make_equiv_classes(pairs)
&gt;&gt;&gt; c2 = group_pairs(pairs)
&gt;&gt;&gt; set(tuple(sorted(x)) for x in c) == set(tuple(sorted(x)) for x in c2)
True
</code></pre>

python list