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

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

https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682

import sys

def valid_ip(ip):
    for s in ip:
        if len(s) == 0 or int(s) > 255 or int(s) < 0:
            return False
    return True

def valid_netmast(netmask):
    string = ""
    for s in netmask:
        if len(s) == 0 or int(s) > 255 or int(s) < 0:
            return False
        string += "{:08b}".format(int(s))
    # 从右往左找1的索引,从左往右找0的索引
    pos_one, pos_zero = string.rfind('1'), string.find('0')
    return pos_zero - pos_one == 1

A, B, C, D, E, error, private = 0, 0, 0, 0, 0, 0, 0

for line in sys.stdin:
    line = line.split("~")
    ip = line[0].split(".")
    netmask = line[1].split(".")
    # 需要忽略的ip地址
    if int(ip[0]) == 127 or int(ip[0]) == 0:
        continue
    # 判断是否合法
    if not valid_ip(ip) or not valid_netmast(netmask):
        error += 1
        continue
    # 按照A/B/C/D/E类地址归类
    if int(ip[0]) <= 126:
        A +=1
    elif int(ip[0]) <= 191:
        B += 1
    elif int(ip[0]) <= 223:
        C += 1
    elif int(ip[0]) <= 239:
        D += 1
    elif int(ip[0]) <= 255:
        E += 1
    # 判断私网IP
    if int(ip[0]) == 10:
        private += 1
    elif int(ip[0]) == 172 and 16 <= int(ip[1]) <= 31:
        private += 1
    elif int(ip[0]) == 192 and int(ip[1]) == 168:
        private += 1
    
print("{} {} {} {} {} {} {}".format(A, B, C, D, E, error, private))

全部评论

相关推荐

11-15 19:28
已编辑
蚌埠坦克学院 硬件开发
点赞 评论 收藏
分享
蚂蚁 基架java (n+6)*16 签字费若干
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务