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

import sys

A = B = C = D = E = M = P = 0

for line in sys.stdin.readlines():
    ip, mask = line.strip().split('~')

    ip = list(ip.split('.'))
    mask = list(mask.split('.'))

    if ip[0] == '0' or ip[0] == '127':
        continue

    msk = ''.join(bin(int(i))[2:].zfill(8) for i in mask) # 没加zfill的时候第7个样例一直wa,降智打击了
    # print(msk)
    pos = msk.index('0') if '0' in msk else -1
    if '' in ip + mask or len(ip) != 4 or len(mask) != 4 or msk == '0' or all(j == '1' for j in  msk) or '1' in msk[pos:] or any(int(i) < 0 or int(i) > 255 for i in ip + mask):
        M += 1
        continue
    # print(ip, mask)
    ip0 = int(ip[0])
    if 0 < ip0 < 127:
        A += 1
        if ip0 == 10:
            P += 1
    elif 127 < ip0 < 192:
        B += 1
        if ip0 == 172 and 16 <= int(ip[1]) < 32:
            P += 1
    elif 191 < ip0 < 224:
        C += 1
        if ip0 == 192 and int(ip[1]) == 168:
            P += 1
    elif 223 < ip0 < 240:
        D += 1
    elif 239 < ip0 < 256:
        E += 1

print(A, B, C, D, E, M, P)

全部评论

相关推荐

点赞 评论 收藏
分享
2024-12-09 14:48
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务