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

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

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

import sys

a = 0
b = 0
c = 0
d = 0
e = 0
error = 0
private = 0


def check_ip(ip: str):
    ip_list = ip.split(".")
    for num in ip_list:
        if not num.isdigit():
            return False

    if len(ip_list) != 4 or "" in ip_list:  # ip 的长度为4 且每一位不为空
        return False

    for i in ip_list:
        if int(i) < 0 or int(i) > 255:  # 检查Ip每一个10位的值范围为0~255
            return False
    return True


def check_mask(mask: str):
    if not check_ip(mask):
        return False

    if mask == "255.255.255.255\n" or mask == "0.0.0.0\n":
        return False

    mask_list = list(map(int, mask.split(".")))
    mask_bin = "".join([bin(mask)[2:].zfill(8) for mask in mask_list])  # 方法一
    # mask_bin = "".join([format(mask, "08b") for mask in mask_list])  # 方法二
    return mask_bin.find("0") == mask_bin.rfind("1") + 1 and mask_bin.startswith("1")


def check_private_ip(ip: str):
    # 三类私网
    ip_list = ip.split(".")
    if ip_list[0] == "10":
        return True
    if ip_list[0] == "172" and 16 <= int(ip_list[1]) <= 31:
        return True
    if ip_list[0] == "192" and ip_list[1] == "168":
        return True
    return False


try:
    for line in sys.stdin:
        ip, mask = line.split("~")
        mask = mask.strip()
        first = int(ip.split(".")[0])
        continue_flag = False

        # 计数时忽略 【0.*.*.*】和【127.*.*.*】
        if first == 0 or first == 127:
            continue

        # 校验IP
        if not check_ip(ip):
            error += 1
            # print('ip error:', ip)
            continue_flag = True
            # 如果有误,就不再检验子网掩码
            continue

        # 校验子网掩码
        if not check_mask(mask):
            # print('mask error:', ip)
            error += 1
            continue

        # 私有IP
        if check_private_ip(ip):
            private += 1

        # A类地址
        if 1 <= first <= 126:
            a += 1

        # B类地址
        elif 128 <= first <= 191:
            b += 1

        # C类地址
        elif 192 <= first <= 223:
            c += 1

        # D类地址
        elif 224 <= first <= 239:
            d += 1

        # E类地址
        elif 240 <= first <= 255:
            e += 1
except:
    pass

print(a, b, c, d, e, error, private)

# 分析:
# 同一行的ip和掩码算作一个,所以ip错误并且掩码错误,都记作一个错误。
# 题目中讲的子网掩码并不是按照标准的子网掩码。

全部评论

相关推荐

06-15 02:05
已编辑
南昌航空大学 数据分析师
Eason三木:你如果想干技术岗,那几个发公众号合唱比赛的经历就去掉,优秀团员去掉,求职没用。然后CET4这种不是奖项,是技能,放到下面的专业技能里或者单独列一个英语能力。 另外好好改改你的排版,首行缩进完全没有必要,行间距好好调调,别让字和标题背景黏在一起,你下面说能做高质量PPT你得展现出来啊,你这简历排版我用PPT做的都能比你做的好。 然后自我评价,你如果要干数据工程师,抗压能力强最起码得有吧。
简历中的项目经历要怎么写
点赞 评论 收藏
分享
见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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