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

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

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

import sys
class IPaddress:
    def __init__(self,num1,num2,num3,num4):
        self.num1 = num1
        self.num2 = num2
        self.num3 = num3
        self.num4 = num4
Acount,Bcount,Ccount,Dcount,Ecount,Miscount,personcount = 0,0,0,0,0,0,0
def justIPmask(ip):
    str1 = ''
    for i in ip:
        str1 += bin(i)[2:].zfill(8)
    if str1[0] == '0':
        return False
    else:
        for e in range(str1.find('0'),len(str1)):
            if str1[e] == '1':
                return False
        else:
            return True
for line in sys.stdin:
    a = line.rstrip('\n').split("~")
    if a == None:
        break
    if a == ['']:
        break
    a0 = list(map(int,a[0].split(".")))
    a1 = list(map(int,a[1].split(".")))
    if a0[0] in [0,127]:
        continue
    if justIPmask(a1):
        ip1 = IPaddress(a0[0],a0[1],a0[2],a0[3])
    else:
        Miscount+=1
        continue
    if 1 <= ip1.num1 <= 126:
        Acount +=1
        if ip1.num1 == 10:
            personcount +=1
    elif 128 <= ip1.num1 <= 191:
        Bcount +=1
        if ip1.num1 == 172 and 16 <= ip1.num2 <= 31:
            personcount +=1
    elif 192 <= ip1.num1 <= 223:
        Ccount +=1
        if ip1.num1 == 192 and ip1.num2 == 168:
            personcount +=1
    elif 224 <= ip1.num1 <= 239:
        Dcount +=1
    elif 240 <= ip1.num1 <= 255:
        Ecount +=1
print(Acount,Bcount,Ccount,Dcount,Ecount,Miscount,personcount)

    

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务