12 April 2007

a merge problem

from here: http://blog.dowski.com/2007/04/12/a-sorting-problem/
from collections import defaultdict

def my_order(ordered, others):
    tmp = defaultdict(list)
    losers = []
    # process others so that,
    # 'id_new', 'id_old' become
    # tmp['id'] = ['id_new', 'id_old']
    for o in others:
        p = o.rfind("_")
        if p == -1:
            losers.append(o)
        else:
            # if o is 'id_new',
            # o[:p] will be 'id'
            tmp[o[:p]].append(o)
    final = []
    for o in ordered:
        final.append(o)
        if o in tmp:
            final.extend(tmp[o])
    return final + losers

my_order(['id', 'age', 'zzyzx', 'bar', 'spam_eggs'],
         ['id_old', 'id_new', 'bar_foo', 'spam_eggs_ham'])

gives
['id', 'id_old', 'id_new', 'age', 'zzyzx',
 'bar', 'bar_foo', 'spam_eggs', 'spam_eggs_ham']