题解 | #识别有效的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))

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

相关推荐

07-11 15:12
门头沟学院 Java
别人在上班,我就在工位上看看视频啥的,这正常吗?
程序员小白条:实习就是摸鱼,只是公司指标,把你进来了,可能那时候客户很多,但等你进来的时候,已经是淡季了,根本没多少需求,或者说根本不适合实习生去完成,因此你就每天干坐着就行,可能1,2个月都没需求
实习生的蛐蛐区
点赞 评论 收藏
分享
Lorn的意义:1.你这根本就不会写简历呀,了解太少了 2.你这些项目经历感觉真的没啥亮点啊,描述的不行,重写书写一下让人看到核心,就继续海投 注意七八月份ofer还是比较多的,越往后机会越少,抓住时机,抓紧检查疏漏,加油查看图片
点赞 评论 收藏
分享
07-09 12:12
门头沟学院 Java
5月底投简历7月初开奖收获秋招第一个offer,虽然白菜价,但至少能保底了
土木转行ing:土木博士想转图像,最后拿了 tp 提前批 sp 最低档,感觉性价比不高
TP-LINK开奖132人在聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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