outline-style sorting algorithm

Anton Vredegoor anton at vredegoor.doge.nl
Thu Apr 29 13:11:36 EDT 2004


"Delaney, Timothy C (Timothy)" <tdelaney at avaya.com> wrote:

>    foo = sorted(foo, key=lambda x: map(int, x.split('.')))
>    print foo

Generality is also about making as little assumptions about the data
as possible and still provide minimal functionality. For example
dropping the "integer" assumption:

def _cmp(x,y):
    L,R = x.split('.'),y.split('.')
    for a,b in zip(L,R):
        r = cmp(len(a),len(b)) or cmp(a,b)
        if r: 
            return r
    return cmp(len(L),len(R))

def test():
    L = ['1.0', '1.0.1', '1.1.1', '1.2',  '1.10',
        '1.11', '1.20', '1.20.1', '1.30', '1.9']
    L.sort(_cmp)
    print L
    
if __name__=='__main__':
    test()

Anton



More information about the Python-list mailing list