outline-style sorting algorithm

wes weston wweston at att.net
Mon Apr 19 11:44:49 EDT 2004


jwsacksteder at ramprecision.com wrote:
> 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.
> 
> Does anyone have pointers to existing code?
> 
> 
> 
> 
> 
> 
> 
> 



list = ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', 
'1.20.1','1.30']

def parse(str):
     list = str.split('.')
     if len(list) > 0:
         x1 = int(list[0])
     else:
         x1 = -1
     if len(list) > 1:
         x2 = int(list[1])
     else:
         x2 = -1
     if len(list) > 2:
         x3 = int(list[2])
     else:
         x3 = -1
     return x1,x2,x3

def cmp(x1,x2):
     w1 = parse(x1)
     w2 = parse(x2)
     if w1[0] < w2[0]:
         return -1
     if w1[0] > w2[0]:
         return 1

     if w1[1] < w2[1]:
         return -1
     if w1[1] > w2[1]:
         return 1

     if w1[2] < w2[2]:
         return -1
     if w1[2] > w2[2]:
         return 1

     return 0

#---------------------------
if __name__ == "__main__":
     list.sort(cmp)
     for x in list:
         print x




More information about the Python-list mailing list