[Tutor] IP sorting

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 26 Dec 2001 22:20:07 -0800 (PST)


On Thu, 27 Dec 2001, Karthik Gurumurthy wrote:

> you have an option to specify a function object along with sort which
> would do the comparison according to your needs Something along the
> following lines should work.
> 
> def func(a,b):
> 
> 	l1 = map(int,a.split('.'))
> 	l2 = map(int,b.split('.'))
> 
> 	for i in range(len(l1)):
> 		first = l1[i]
> 		sec = l2[i]
> 
> 		if first == sec:
> 			continue;
> 		elif first > sec:
> 			return 1
> 		else:
> 			return -1
> 	else:
> 		return 0


Here's a a simplification of the code:

###
def cmpIPAddresses(a, b):
    l1 = map(int, a.split('.'))
    l2 = map(int, b.split('.'))
    return cmp(l1, l2)
###


This relies on the fact that Python knows how to compare two sequences:


###
>>> cmp([1, 2, 3], [1, 2, 3])
0
>>> cmp([1, 2, 3], [1, 2, 4])
-1
>>> cmp([3, 2, 1], [1, 2, 3])
1
>>> cmp([3, 2, 1], [1, 2, 3])
###

Let Python do the work.  *grin*