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

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

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



def check_mask(mask):
    # -1非法 1合法
    # 掩码
    if check_ip(mask) == -1:
        return -1
    if mask in ["255.255.255.255", "0.0.0.0"]:
        return -1

    mask_sp = mask.split('.')
    if len(mask_sp) !=4:
        return -1
    temp_s = ""
    for m in mask_sp:
        temp_s += bin(int(m))[2:].rjust(8,'0')  # "0b001" 去掉0b 补齐八位
    # 1111000
    if temp_s[temp_s.index('0'):].count('1') != 0:
        return -1

    return 1


def check_ip(ip):
    ip_sp = ip.split('.')
    if len(ip_sp) != 4 or '' in ip_sp:
        return -1
    for i in ip_sp:
        if int(i) < 0 or int(i) > 255:
            return -1

    return 1


error = 0
private = 0
kind_ct = [0, 0, 0, 0, 0]
while True:
    try:
        ip, mask = input().split('~')
        if ip.split('.')[0] in ['0','127']:
            continue
        elif check_ip(ip) == -1 or check_mask(mask) == -1:
            error += 1
        elif check_ip(ip) == 1 and check_mask(mask) == 1:
            ip_sp = list(map(int, ip.split('.')))
            if ip_sp[0] <= 126:
                kind_ct[0] += 1
            elif ip_sp[0] <= 191:
                kind_ct[1] += 1
            elif ip_sp[0] <= 223:
                kind_ct[2] += 1
            elif ip_sp[0] <= 239:
                kind_ct[3] += 1
            elif ip_sp[0] <= 255:
                kind_ct[4] += 1

            if ip_sp[0] == 10:
                private += 1
            elif ip_sp[0] == 172 and 16 <= ip_sp[1] <= 32:
                private += 1
            elif ip_sp[0] == 192 and ip_sp[1] == 168:
                private += 1

    except:
        break


out = kind_ct + [error] + [private]
for n in out:
    print(n, end=" ")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务