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

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

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

import re

a_num = 0
b_num = 0
c_num = 0
d_num = 0
e_num = 0
s_num = 0
err_num = 0
def is_numeric(s):
    try:
        num = int(s)
        if 0 <= num <= 255:
            return True
        else:
            return False
    except ValueError:
        return False


def belongIp(ip,ym_arr):
    global a_num
    global b_num
    global c_num
    global d_num
    global e_num
    global s_num
    ip_arr = [int(x) for x in ip.split(".")]
    if (
        1 <= ip_arr[0] <= 126
        and 0 <= ip_arr[1] <= 255
        and 0 <= ip_arr[2] <= 255
        and 0 <= ip_arr[3] <= 255
    ):
        a_num += 1
        # print(ip, ym_arr)
        if ip_arr[0] == 10:
            s_num += 1
    elif (
        128 <= ip_arr[0] <= 191
        and 0 <= ip_arr[1] <= 255
        and 0 <= ip_arr[2] <= 255
        and 0 <= ip_arr[3] <= 255
    ):
        b_num += 1
        if ip_arr[0] == 172 and 16 <= ip_arr[1] <= 31:
            s_num += 1
    elif (
        192 <= ip_arr[0] <= 223
        and 0 <= ip_arr[1] <= 255
        and 0 <= ip_arr[2] <= 255
        and 0 <= ip_arr[3] <= 255
    ):
        c_num += 1
        if ip_arr[0] == 192 and ip_arr[1] == 168:
            s_num += 1
    elif (
        224 <= ip_arr[0] <= 239
        and 0 <= ip_arr[1] <= 255
        and 0 <= ip_arr[2] <= 255
        and 0 <= ip_arr[3] <= 255
    ):
        d_num += 1
    elif (
        240 <= ip_arr[0] <= 255
        and 0 <= ip_arr[1] <= 255
        and 0 <= ip_arr[2] <= 255
        and 0 <= ip_arr[3] <= 255
    ):
        e_num += 1
# arr = input().split()
# print(arr)
# for index in range(len(arr)):
while True:
    try:
        s = input().split("~")
        # s = arr[index].split("~")
        ip_arr = s[0].split(".")
        ip_arr_h = [x for x in ip_arr if is_numeric(x)]
        ym_arr = [str(bin(int(v))).replace("0b", "").zfill(8) for v in s[1].split(".")]
        isYm = re.match(r"^1+0+$", "".join(ym_arr))
        if len(ip_arr_h) == 4 and len(ip_arr) == 4:
            if ip_arr_h[0] != '0' and ip_arr_h[0] != '127': 
                if isYm:
                    belongIp(s[0],ym_arr)
                else:
                    err_num += 1   
        else:
            err_num += 1
    except:
        break
print(a_num, b_num, c_num, d_num, e_num, err_num, s_num)



代码还没优化,只是一步一步先列推导出来,这个题有大坑:

  1. ip如果合法且是0或者127开头,那么不管掩码是否不合法,不参与计数,意思就是错误也不计
  2. 掩码二进制每个数字不足8位,需左边补位0,计算机的可能了解这个,非计算机的会被坑
  3. ip的每个数字最大255,超过255是非法的ip,了解ip的会知道这一点。
全部评论

相关推荐

威猛的小饼干正在背八股:挂到根本不想整理
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务