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

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

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

Type_Counter = {
    'A' : 0,
    'B' : 0,
    'C' : 0,
    'D' : 0,
    'E' : 0,
    'Private_IP' : 0,
    'Error_IP_and_Mask' : 0
    }

Wrong_IP = []

def Judge_Mask(mask):
    if mask in Wrong_IP:
        return False

    if mask == [255, 255, 255, 255] or mask == [0, 0, 0, 0]:
        return False

    m = ''

    for i in range(4):
        m += bin(mask[i])[2:].zfill(8)
    one_end_index = m.rfind('1')
    zero_start_index = m.find('0')
    if zero_start_index - one_end_index == 1:
        return True
    else:
        return False 

def Judge_IP(ip, mask):
    if ip[0] in range(1, 127) and ip[1] in range(0, 256) and ip[2] in range(0, 256) and ip[3] in range(0, 256) and Judge_Mask(mask):
        Type_Counter['A'] += 1
        return True
    elif ip[0] in range(128, 192) and ip[1] in range(0, 256) and ip[2] in range(0, 256) and ip[3] in range(0, 256) and Judge_Mask(mask):
        Type_Counter['B'] += 1
        return True
    elif ip[0] in range(192, 224) and ip[1] in range(0, 256) and ip[2] in range(0, 256) and ip[3] in range(0, 256) and Judge_Mask(mask):
        Type_Counter['C'] += 1
        return True
    elif ip[0] in range(224, 240) and ip[1] in range(0, 256) and ip[2] in range(0, 256) and ip[3] in range(0, 256) and Judge_Mask(mask):
        Type_Counter['D'] += 1
        return True
    elif ip[0] in range(240, 256) and ip[1] in range(0, 256) and ip[2] in range(0, 256) and ip[3] in range(0, 256) and Judge_Mask(mask):
        Type_Counter['E'] += 1
        return True
    elif ip[0] == 127 or ip[0] == 0:
        return False
    else:
        Type_Counter['Error_IP_and_Mask'] += 1
        Wrong_IP.append(ip)
        return False

def Judge_PrivateIP(ip):
    if IP in Wrong_IP:
        return False

    if ip[0] == 10 and ip[1] in range(0, 256) and ip[2] in range(0, 256) and ip[3] in range(0, 256):
        Type_Counter['Private_IP'] += 1
        return True
    elif ip[0] == 172 and ip[1] in range(16, 32) and ip[2] in range(0, 256) and ip[3] in range(0, 256):
        Type_Counter['Private_IP'] += 1
        return True
    elif ip[0] == 192 and ip[1] == 168 and ip[2] in range(0, 256) and ip[3] in range(0, 256):
        Type_Counter['Private_IP'] += 1
        return True
    else:
        return False


while 1:
    try:
        s = input()
        
        if '..' in s or '...' in s:
            Type_Counter['Error_IP_and_Mask'] += 1
        else:
            IP = list(map(int, s.split('~')[0].split('.')))
            Mask = list(map(int, s.split('~')[1].split('.')))

            Judge_IP(IP, Mask)
            Judge_PrivateIP(IP)

    
    except:
        break

print(Type_Counter['A'], Type_Counter['B'], Type_Counter['C'], Type_Counter['D'], Type_Counter['E'], Type_Counter['Error_IP_and_Mask'], Type_Counter['Private_IP'])

思路不难,耐心、细心、恒心,相信自己!一定能行!

全部评论

相关推荐

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