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

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

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

import sys

a = b = c = d = e = wrong = p = 0

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

    # 处理IP地址问题
    address = ip.split(".")
    
    if len(address) != 4:
        wrong += 1
        continue

    digit_adrress = []
    worn_flag =0
    for x in address:  # 无法转为字符串就报错
        try:
            digit = int(x)
            if 0<=digit<= 255:
                digit_adrress.append(digit)
            else:
                wrong += 1
                worn_flag = 1
                break
        except:
            wrong += 1
            worn_flag = 1
            break

    if worn_flag == 1:
        continue

    first_digit = digit_adrress[0]

    if first_digit in {127, 0}:
        continue  # 【0.*.*.*】和【127.*.*.*】类型地址忽略


    masks = mask.split('.')
    mask_digits = []
    worn_flag =0
    for x in masks:
        try:
            digit = int(x)
            mask_digits.append(digit)
        except:
            wrong += 1
            worn_flag = 1
            break
    if worn_flag == 1:
        continue

    
    alls =''
    for x in mask_digits:
        alls += format(x, '08b')

    one_conut = sum(x =='1' for x in alls)
    manual_one_count = 0

    for x in alls:
        if x == '1':
            manual_one_count +=1
        else:
            break
    
    if one_conut == 0 or one_conut == 32:
        wrong += 1
        continue
    
    if one_conut != manual_one_count:
        wrong += 1
        continue

    



    
    second_digit = digit_adrress[1]
    

    if first_digit == 10:
        p+=1

    if first_digit == 172:
        if 16<=second_digit<=31:
            p+=1

    if first_digit == 192:
        if second_digit==168:
            p+=1

    if 1<=first_digit<=126:
        a+=1
    if 128<=first_digit<=191:
        b+=1
    if 192<=first_digit<=223:
        c+=1
    if 224<=first_digit<=239:
        d+=1
    if 240<=first_digit<=255:
        e+=1


print(a,b,c,d,e,wrong,p)

屎山代码

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-27 10:52
点赞 评论 收藏
分享
暴走萝莉莉:这是社招场吧,作为HR说个实话:这个维护关系的意思是要有政府资源,在曾经的工作中通过人脉资源拿下过大订单的意思。这个有相关管理经验,意思也是真的要有同岗位经验。应酬什么的对于业务成交来说就算不乐意也是常态,就是要求说话好听情商高,酒量好。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务