outline-style sorting algorithm

Thorsten Kampe thorsten at thorstenkampe.de
Wed Apr 28 20:27:33 EDT 2004


* jwsacksteder at ramprecision.com (2004-04-19 15:08 +0100)
> I have a need to sort a list of elements that represent sections of a
> document in dot-separated notation. The built in sort does the wrong thing.
> This seems a rather complex problem and I was hoping someone smarter than me
> had already worked out the best way to approach this. For example, consider
> the following list-
> 
>>>> foo
> ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', '1.20.1',
> '1.30']
>>>> foo.sort()
>>>> foo
> ['1.0', '1.0.1', '1.1.1', '1.10', '1.11', '1.2', '1.20', '1.20.1', '1.30',
> '1.9']
> 
> Obviously 1.20.1 should be after 1.9 if we look at this as dot-delimited
> integers, not as decimal numbers.

You need some general approach to avoid the DSU thing:

def funcsort(seq, func):
    """ sort seq by func(item) """
    seq = seq[:]
    seq.sort(lambda x, y: cmp(func(x), func(y)))
    return seq

funcsort(foo, lambda x: map(int, x.split('.')))


Thorsten



More information about the Python-list mailing list