题解 | 识别有效的IP地址和掩码并进行分类统计

def is_valid_ip(ip):
    parts = ip.split('.')
    if len(parts) != 4:
        return False
    for part in parts:
        if not part.isdigit() or not 0 <= int(part) <= 255:
            return False
    # 检查特定的无效IP地址
    return True


def is_valid_subnet(subnet):
    if not is_valid_ip(subnet):
        return False
    if subnet == '255.255.255.255' or subnet == '0.0.0.0':
        return False
    parts = subnet.split('.')
    if len(parts) != 4:
        return False
    for part in parts:
        if not part.isdigit() or not 0 <= int(part) <= 255:
            return False
    binary = ''.join(format(int(x), '08b') for x in parts)
    sum1 = 0
    sum2 = binary.count('1')
    for b in binary:
        if b == '1':
            sum1 += 1
        else:
            break

    if sum1 == sum2:
        return True
    else:
        return False


def classify_ip(ip):
    parts = list(map(int, ip.split('.')))
    if 1 <= parts[0] <= 126:
        # print(ip)
        return 'A'
    elif 128 <= parts[0] <= 191:
        return 'B'
    elif 192 <= parts[0] <= 223:
        return 'C'
    elif 224 <= parts[0] <= 239:
        return 'D'
    elif 240 <= parts[0] <= 255:
        return 'E'
    return None


def is_private_ip(ip):
    parts = list(map(int, ip.split('.')))
    return parts[0] == 10 or (parts[0] == 172 and 16 <= parts[1] <= 31) or (parts[0] == 192 and parts[1] == 168)


# 初始化计数器
counts = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'error': 0, 'private': 0}

# 读取输入直到文件结尾
try:
    while True:
        line = input()
        if not line:
            break
        ip, subnet = line.split('~')
        parts = ip.split('.')

        # 检查IP和子网掩码的有效性
        if parts[0] == '127' or int(parts[0]) == '0':
            continue
        elif not is_valid_ip(ip) or not is_valid_subnet(subnet):
            counts['error'] += 1
        else:
            ip_class = classify_ip(ip)
            if ip_class:
                counts[ip_class] += 1
            if is_private_ip(ip):
                counts['private'] += 1
except EOFError:
    pass

# 输出结果
print(' '.join(
    map(str, [counts['A'], counts['B'], counts['C'], counts['D'], counts['E'], counts['error'], counts['private']])))

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务