[Tutor] IP sorting

Jeff Shannon jeff@ccvcorp.com
Thu, 27 Dec 2001 10:03:19 -0800

> "Grimmtooth" <grimmtoothtoo@yahoo.com> wrote:
> > How to sort domain names AND IP addresses? NB. Domain names better to sort
> > starting from level 1.
> >
> > bbb.aa
> > aaa.bb
> > ccc.cc
> I'm sure someone more familiar with Python than I will have a slicker
> solution, but I believe that if you split() the components of such things
> into an array of tuples [(bbb,aa), (aaa,bb), (ccc.cc)] then you can compare
> each tuple directly, e.g. (bbb,aa) > (aaa,bb). From there it should be a
> fairly easy excercise to do the actual sort.

Yes, but it'll sort them in the "wrong" order--you want all *.com names to come
before all *.net names (or so sayeth the spec given by Roman Suzi ;) ).  In order to
do this *just* for symbolic domain names, you could try this:

def sort_domains(domainlist):
    templist = [item.split('.') for item in domainlist]
    for line in templist:
    for line in templist:
    return ['.'.join(line) for line in templist]

This should sort domain names such that 'news.somename.com' will be right next to
'www.somename.com', but likely some distance from 'www.somename.net', which seems to
be the most appropriate sorting order for domain names.

However, this still doesn't fulfill the original spec, which asked to sort a mixed
list of domain names and numeric IP addresses...   I suppose that one could do
something like:

def sort_domains_and_IPs(unsortedlist):
    list1, list2 = segregate_IPs(unsortedlist)
    list1 = sort_IPs(list1)
    list2 = sort_domains(list2)
    return list1

wherein I assume that all numeric IP addresses should sort before all named domains
(and use previously discussed sorting for IPs).  The implementation of
segregate_IPs() is the only problem remaining--I suppose that one could try map(int,
addr.split('.')), and if a ValueError is raised, assume it's a named domain...

def segregate_IPs(addresses):
    IPs = []
    domains = []
    for addr in addresses:
            l = map(int, addr.split('.'))
        except ValueError:
    return IPs, domains

This looks like it ought to work, but it's untested and strictly off the top of my
head.  It's also probably horribly inefficient.  :)

Jeff Shannon
Credit International