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

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

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

这里的主要难点是子网掩码的判断,并不是只有255和0,需要转换成二进制

import sys

def is_valid_ip(lst):
    try:
        if any(i == '' for i in lst):
            return False
        return all(0 <= int(i) <= 255 for i in lst) and len(lst) == 4
    except ValueError:
        return False
        
def is_valid_sm(lst):
    try:
        if any(i == '' for i in lst) or len(lst) != 4 :
            return False
        decimal_value = (int(lst[0]) << 24) + (int(lst[1]) << 16) + (int(lst[2]) << 8) + int(lst[3])
        _str=    '{:032b}'.format(decimal_value)
		
        if '1' not in _str or '0' not in _str or '01' in _str:
            return False
        
        return True
    except ValueError:
        return False

res = {
    'A': 0,
    'B': 0,
    'C': 0,
    'D': 0,
    'E': 0,
    'F': 0,
    'G': 0,
}

try:

    while True:
        ip, sm = input().split('~')
        ip_list = list(map(str, ip.split('.')))
        sm_list = list(map(str, sm.split('.')))

        if ip_list[0] in [0, 127,'0','127']:
            continue

        
        if not is_valid_ip(ip_list) or not is_valid_sm(sm_list):
            res['F'] += 1
            #print(f'{ip_list} {sm_list}')
            continue

        ip_list = list(map(int, ip_list))

        if ip_list[0] < 128:
            res['A'] += 1
            if ip_list[0] == 10 or (ip_list[0] == 172 and 31 >= ip_list[1] >= 16):
                res['G'] += 1
        elif ip_list[0] < 192:
            res['B'] += 1
        elif ip_list[0] < 224:
            res['C'] += 1
            if ip_list[0] == 192 and ip_list[1] == 168:
                res['G'] += 1
        elif ip_list[0] < 240:
            res['D'] += 1
        else:
            res['E'] += 1


except EOFError:
    val = list(map(str, res.values()))
    print(' '.join(val))

#在找工作求抱抱#
全部评论

相关推荐

难怪不开摄像头,全是简单的性格题,比大疆友善多了
NULL10086:今早上发的测评,我这还没做呢,官网上已经显示挂了
投递大疆等公司7个岗位
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-11 13:34
offe从四面八方来:我真的没时间陪你闹了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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