def compress_domain(hostnames):
    """
    Compress a list of hosts in a domain into a more compact representation
    """
    hostnames.sort()
    prev_dict = {'prefix': "", 'suffix': '', 'number': 0}
    items = []
    items_block = []
    new_hosts = []
    for host in hostnames:
        try:
            parsed_dict = re.match(
                r"(?P<prefix>[^0-9]+)(?P<number>\d+)(?P<suffix>.*).?",
                host
            ).groupdict()
            # To generate the range we need the entries sorted numerically
            # but to ensure we don't loose any leading 0s we don't want to
            # replace the number parameter that is a string with the leading
            # 0s.
            parsed_dict['number_int'] = int(parsed_dict['number'])
            new_hosts.append(parsed_dict)
        except __HOLE__:
            if '.' not in host:
                host += '.'
                parsed_dict = {'host': compress([host])[0].strip('.')}
            else:
                parsed_dict = {'host': host}
            new_hosts.append(parsed_dict)
    new_hosts = multikeysort(new_hosts, ['prefix', 'number_int'])
    for parsed_dict in new_hosts:
        if 'host' in parsed_dict.keys() or \
                parsed_dict['prefix'] != prev_dict['prefix'] or \
                parsed_dict['suffix'] != prev_dict['suffix'] or \
                int(parsed_dict['number']) != int(prev_dict['number']) + 1:
            if len(items_block):
                items.append(items_block)
            items_block = [parsed_dict]
        else:
            items_block.append(parsed_dict)
        prev_dict = parsed_dict
    items.append(items_block)
    result = []
    for item in items:
        if len(item):
            if len(item) == 1 and 'host' in item[0].keys():
                result.append(item[0]['host'])
            elif len(item) == 1:
                result.append(
                    '%s%s%s' % (
                        item[0]['prefix'], item[0]['number'], item[0]['suffix']
                    )
                )
            else:
                result.append(
                    '%s[%s-%s]%s' % (
                        item[0]['prefix'],
                        item[0]['number'],
                        item[-1]['number'],
                        item[0]['suffix']
                    )
                )
    return result
dataset/ETHPy150Open dwighthubbard/hostlists/hostlists/hostlists.py/compress_domain