首页 > 试题广场 >

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

[编程题]识别有效的IP地址和掩码并进行分类统计
  • 热度指数:329088 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

请解析IP地址和对应的掩码,进行分类识别。要求按照A/B/C/D/E类地址归类,不合法的地址和掩码单独归类。

所有的IP地址划分为 A,B,C,D,E五类

A类地址从1.0.0.0到126.255.255.255;

B类地址从128.0.0.0到191.255.255.255;

C类地址从192.0.0.0到223.255.255.255;

D类地址从224.0.0.0239.255.255.255;

E类地址从240.0.0.0255.255.255.255


私网IP范围是:

从10.0.0.0到10.255.255.255

从172.16.0.0到172.31.255.255

从192.168.0.0到192.168.255.255


子网掩码为二进制下前面是连续的1,然后全是0。(例如:255.255.255.32就是一个非法的掩码)
(注意二进制下全是1或者全是0均为非法子网掩码)

注意:
1. 类似于【0.*.*.*】和【127.*.*.*】的IP地址不属于上述输入的任意一类,也不属于不合法ip地址,计数时请忽略
2. 私有IP地址和A,B,C,D,E类地址是不冲突的



输入描述:

多行字符串。每行一个IP地址和掩码,用~隔开。

请参考帖子https://www.nowcoder.com/discuss/276处理循环输入的问题。


输出描述:

统计A、B、C、D、E、错误IP地址或错误掩码、私有IP的个数,之间以空格隔开。

示例1

输入

10.70.44.68~255.254.255.0
1.0.0.1~255.0.0.0
192.168.0.2~255.255.255.0
19..0.~255.255.255.0

输出

1 0 1 0 0 2 1

说明

10.70.44.68~255.254.255.0的子网掩码非法,19..0.~255.255.255.0的IP地址非法,所以错误IP地址或错误掩码的计数为2;
1.0.0.1~255.0.0.0是无误的A类地址;
192.168.0.2~255.255.255.0是无误的C类地址且是私有IP;
所以最终的结果为1 0 1 0 0 2 1        
示例2

输入

0.201.56.50~255.255.111.255
127.201.56.50~255.255.111.255

输出

0 0 0 0 0 0 0

说明

类似于【0.*.*.*】和【127.*.*.*】的IP地址不属于上述输入的任意一类,也不属于不合法ip地址,计数时请忽略         
#注意,此题优先判定掩码是否错误,然后才是0,127开头的IP跳过。 如果以127开头的IP但是掩码是错误的则属于错误不能跳过,详见第八组数据
#根据题目要求可以取巧拼接4个二进制,除了0.0.0.1情况外出现'01'就是非法 日常替换 &nbs***bsp; 为 or,程序一放上来就这鸟毛病
finalerr =0
A=0
B=0
C=0
D=0
E=0
private = 0
check =0
strpri = ""#初始各种玩意
while True:
    try:
        low, high = input().split("~")#以~分为IP和掩码
        lowlist = low.split(".")#以。分为不同项
        highlist = high.split(".")
        error = 0
        check1 = 0
        check2 = 0
        straa =""#每次初始化判定和计数器
        if len(lowlist) != 4 &nbs***bsp; len(highlist) !=4:#当长度不为4时直接算作错误
            finalerr = finalerr+1 
        else:#确定长度为4时
            for i in range (4):#遍历四遍
                if int(highlist[i]) ==0:#计算0的个数,看看是否全为零
                    check1 = check1 +1
                if int(highlist[i]) ==255:#计算255的个数,看看是否全为255
                    check2 = check2 +1
                if "" not in lowlist and "" not in highlist and 0<=int(lowlist[i]) <=255 and 0<=int(highlist[i]) <=255:
                    str1=str(bin(int(highlist[i])))#判断每一项在0-255之间,并不为空时,转换为二进制str
                    str1=str1.replace('0b','')#去除‘0b’开头
                    str1=str1.rjust(8,'0')#补位成为八位二进制
                    straa=straa+str1
                else:#其他情况如为空或者不在范围内视为非法
                    error =1
            if check1==4 &nbs***bsp; check2==4 :#当全为0或全为1时非法
                error = 1
            if '01' in straa and straa !='00000000000000000000000000000001':#只要出现‘01’ 则是非法,除了0.0.0.1
                error =1
        if error == 1:#当判断为非法时,非法计数+1
            finalerr = finalerr + 1
        elif 126 >= int(lowlist[0]) >= 1:#A的计数
            A = A+1
        elif 191>= int(lowlist[0]) >= 128:#B
            B = B+1
        elif 223 >= int(lowlist[0]) >= 192:#C
            C = C+1
        elif 239 >= int(lowlist[0]) >= 224:#D
            D = D+1
        elif 255 >= int(lowlist[0]) >= 240:#E
            E = E+1
        elif int(lowlist[0]) == 0 &nbs***bsp; int(lowlist[0]) ==127:#合法前提下,跳过计数,可不要这两行只是把这个可能性写出来
            error = 0#什么都不做跳过
        if int(lowlist[0]) == 10 and error != 1:#继续判断私有
            private = private +1
        elif int(lowlist[0]) == 172 and 31 >= int(lowlist[1]) >= 16  and error != 1:
            private = private +1
        elif int(lowlist[0]) == 192 and int(lowlist[1]) == 168 and error != 1:
            private = private +1
    except:
        break
strpri= str(A) + " " + str(B) + " " + str(C) + " " + str(D) + " " + str(E) + " " + str(finalerr) + " " + str(private)
print(strpri)#整体输出
#16 6 3 1 0 14 0 为第八组结果,如果错误为13代表跳过了127但是掩码属于非法

编辑于 2021-07-01 14:42:42 回复(1)
开始连题目都没看懂 研究了好久 加上百度一直调试 才通过 
a=b=c=d=e=f=g = 0

while 1:
    try:
        n = input()
        if n == '':
            break

        n1,n2 = n.split('~')
        m1 = n1.split('.')
        m2 = n2.split('.')
        #判断是否合法

        for i in m1:
            if i == '':
                flag = False
                break
            if int(i) >= 0 and int(i) <= 255:
                flag = True
        if flag == False:
            f += 1
            continue

        s = ''
        flag1 = False
        for j in m2:
            t = str(bin(int(j)))[2:]
            for i in range(8-len(t)):
                s = s+'0'
            s = s + t
        
        for k in range(len(s)-1):
            if int(s[k]) < int(s[k+1]):
                flag1 = True

        if s[0] == s[-1]:
            flag1 = True

        if flag1:
            f += 1
            continue
       #区分A B C D E G
        if 1 <= int(m1[0]) <= 126:
            a += 1
            if int(m1[0]) == 10:
                g += 1
        elif 128 <= int(m1[0]) <= 191:
            b += 1
            if int(m1[0]) == 172 and 16 <= int(m1[1]) <= 31:
                g += 1
        elif 192 <= int(m1[0]) <= 223:
            c += 1
            if int(m1[0]) == 192 and int(m1[1]) == 168:
                g += 1
        elif 224 <= int(m1[0]) <= 239:
            d += 1
        elif int(m1[0]) >= 240 and int(m1[0]) <= 255:
            e += 1



    except:
        break

print('{0} {1} {2} {3} {4} {5} {6}'.format(a,b,c,d,e,f,g))


发表于 2021-06-03 15:41:39 回复(0)
子网掩码的校验尝试了另外一种方法
# IP校验规则:根据分类校验第一位范围
def chk_ip(ip):
    for i in ip.split('.'):
        try :
            if 0<=int(i)<=255:
#                 return True
                  pass
            else:
                return False
        except:
            return False
    return True
# 子网掩码校验规则,前面权威1,后面全为0,转换为二进制,找出0开始的位置和1结束的位置的差
def chk_mask(mask):
    result=[]
    for m in mask.split('.'):
        m_b = bin(int(m))
        b = m_b[2:]
        result.append(b.zfill(8))
    mask_str = ''.join(result)
    zero_start = mask_str.find('0')
    one_end = mask_str.rfind('1')
    if zero_start - one_end == 1:
        return True
    else:
        return False
A=B=C=D=E=ERR=PRI=0
ip=[]
mask=[]
try:
    while True:
        s_ip ,s_mask = input().split("~")
        if chk_ip(s_ip) and chk_mask(s_mask):
            ip = [ int(i) for i in s_ip.split('.')]
            mask = [ int(i) for i in s_mask.split('.')] 
            if 1 <= ip[0] <= 126:
                A+=1
            if 128 <= ip[0] <= 191:
                B+=1
            if 192 <= ip[0] <= 223:
                C+=1
            if 224 <= ip[0] <= 239:
                D+=1
            if 240 <= ip[0] <= 255:
                E+=1
            if ip[0] == 10 or (ip[0] == 17 and 16<=ip[1]<= 31) or (ip[0] == 192 and ip[1]== 168):
                PRI+=1
        else:
            ERR += 1
except:
    print("%s %s %s %s %s %s %s" %(A, B ,C ,D ,E ,ERR, PRI))
发表于 2021-05-28 00:14:29 回复(0)
用正则检查IP合法性,感觉还行。。拙作。。
import re

cla, clb, clc, cld, cle, wrong, pers = 0, 0, 0, 0, 0, 0, 0
while True:
    try:
        a = input()
        b = a.strip().partition('~')
        ip = b[0]
        mask = b[2]
        ips = b[0].split('.')
        masks = b[2].split('.')
        flag = 1
        has_zero = 0
        mask_wrong = 0
        if mask == '255.255.255.255' or mask == '0.0.0.0':
            wrong += 1
            continue
        else:
            for m in masks:
                if m == '0':
                    has_zero = 1
                if m not in ['255', '254', '252', '248', '240', '224', '192', '128', '0']:
                    wrong += 1
                    mask_wrong = 1
                    break
                if m in ['254', '252', '248', '240', '224', '192', '128'] and has_zero == 0:
                    flag = 0
                    continue
                if (flag == 0 and m != '0') or (has_zero == 1 and m != '0'):
                    wrong += 1
                    mask_wrong = 1
                    break
        if mask_wrong != 0:
            continue
        k = re.match(r'^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|'
               r'25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|'
               r'2[0-4][0-9]|25[0-5])$', ip)
        if k is None:
            wrong += 1
            continue
        if 1 <= int(ips[0]) <= 126:
            cla += 1
        elif 128 <= int(ips[0]) <= 191:
            clb += 1
        elif 192 <= int(ips[0]) <= 223:
            clc += 1
        elif 224 <= int(ips[0]) <= 239:
            cld += 1
        elif 240 <= int(ips[0]) <= 255:
            cle += 1
        if ips[0] == '10' or (ips[0] == '192' and ips[1] == '168') or (ips[0] == '172' and 16 <= int(ips[1]) <= 31):
            pers += 1
        
    except:
        print('{} {} {} {} {} {} {}'.format(cla, clb, clc, cld, cle, wrong, pers))
        break
 
发表于 2021-05-08 16:51:35 回复(0)
import sys

test_data = [d.strip() for d in sys.stdin.readlines()]


a_l, b_l, c_l, d_l, e_l, error_l, person_l, = 0, 0, 0, 0, 0, 0, 0


def if_a_ip(ip_int):
    ret_l = ip_int.split(".")
    if 1 <= int(ret_l[0]) <= 126:
        return True
    else:
        return False
    

def if_b_ip(ip_int):
    ret_l = ip_int.split(".")
    if 128 <= int(ret_l[0]) <= 191:
        return True
    else:
        return False
    
def if_c_ip(ip_int):
    ret_l = ip_int.split(".")
    if 192 <= int(ret_l[0]) <= 223:
        return True
    else:
        return False
    
    
def if_d_ip(ip_int):
    ret_l = ip_int.split(".")
    if 224 <= int(ret_l[0]) <= 239:
        return True
    else:
        return False
    
    
def if_e_ip(ip_int):
    ret_l = ip_int.split(".")
    if 240 <= int(ret_l[0]) <= 255:
        return True
    else:
        return False

def if_valid_ym(ym):
    int_list = ym.split(".")
    ret_l = [i for i in int_list if i.isalnum() and 0<=int(i)<=255 and len(i) != 2]
    if len(ret_l) < 4:
        return False
    ret = ""
    for i in int_list:
        bin_s = f"{str(bin(int(i))).replace('0b', '')}".rjust(8, "0")
        ret += bin_s

    check_l = ret.rsplit("1", 1)
    if "0" not in check_l[0] and "1" not in check_l[1] and "0" in check_l[1]:
        return True
    else:
        return False
    
def if_valid_ip(ip):
    int_list = ip.split(".")
    ret_l = [i for i in int_list if i.isalnum() and 0<=int(i)<=255]
    
    if len(ret_l) < 4:
        return False
    elif ret_l[0] == "0" or ret_l[0] == "127":
        return None
    else:
        return True
    
def if_personal_ip(ip):
    int_list = ip.split(".")
    if int_list[0] == "10" or ( len(int_list[0])==3 and 17216 <= int(int_list[0] + int_list[1]) <= 17231) or (int_list[0] + int_list[1]) == "192168":
        return True
    else:
        return False
    
for d in test_data:
    ip, mask = d.split("~")
    mask_flag = if_valid_ym(mask)
    ip_flag = if_valid_ip(ip)
    
    if mask_flag is False or ip_flag is False:
        error_l += 1
        continue
    if ip_flag is None:
        continue
    if if_a_ip(ip):
        a_l += 1
    elif if_b_ip(ip):
        b_l += 1
    elif if_c_ip(ip):
        c_l += 1
    elif if_d_ip(ip):
        d_l += 1
    elif if_e_ip(ip):
        e_l += 1
        
    if if_personal_ip(ip):
        person_l +=1
        
print(a_l, b_l, c_l, d_l, e_l, error_l, person_l, sep=" ")
    

    
发表于 2021-04-11 13:43:47 回复(0)
1. 自测用例的预期输出有问题,和提交后的测试用例关于私有IP的规则不一样
2. 想请教255.16.0.0以及255.255.255.32是否可以作为合法子网掩码?
前者没有违反题意,但测试用例里不能通过。后者也没违反题意,但看网上对子网掩码的科普,好像最后一位除了0之外最小只能取到192还是128?
3. 以下代码能通过所有测试用例,但是子网掩码那段基本上是结合题意、网上科普和测试用例推出来的,不忍直视😓
import re

def validate_ip(str):
    error = 0
    if not re.findall('[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+', str):
        error = 1
    elif error == 0:
        for x in map(int, str.split('.')):
            if x > 255:
                error = 2
    return error

def validate_mask(str):
    mask_error = 0
    mask = str.split('.')
    for i in range(4):
        mask[i] = bin(int(mask[i], 10))
    output = ''.join(mask).replace('0b', '')
    if not re.findall('[1]+[0]+', output) or len(max(re.findall('[1]+[0]+', output), key=len)) < len(output):
        mask_error = 1
    #以上部分对于224.109.93.237~255.16.0.0判断错误,增加以下判断
    FIRST = [255]
    SECOND = [255, 0]
    THIRD = [255, 254, 252, 248, 240, 224, 192, 128, 0]
    FOURTH = [252, 248, 240, 224, 192, 128, 32, 0]
    for i in range(4):
        mask[i] = int(mask[i], 2)
    if (mask[0] not in FIRST) | (mask[1] not in SECOND) | (mask[2] not in THIRD) | (mask[3] not in FOURTH):
        mask_error = 1
    if (mask[1] == 0 & mask[2] > 0) | (mask[2] == 0 & mask[3] > 0):
        mask_error = 1
    if (mask[1] < mask[2]) | (mask[2] < mask[3]):
        mask_error = 1
    return mask_error

def categorize(str):
    ip = list(map(int, str.split('.')))
    category = ''
    if 1 <= ip[0] <= 126:
        category = 'A'
    elif 128 <= ip[0] <= 191:
        category = 'B'
    elif 192 <= ip[0] <= 223:
        category = 'C'
    elif 224 <= ip[0] <= 239:
        category = 'D'
    elif 240 <= ip[0] <= 255:
        category = 'E'
    return category

def is_private(str):
    ip = list(map(int, str.split('.')))
    is_private = 0
    if ip[0] == 10 | (ip[0] == 172 & 16 <= ip[1] <= 31) | (ip[0] == 192 & ip[1] == 168):
        is_private = 1
    return is_private

cnt_a = 0
cnt_b = 0
cnt_c = 0
cnt_d = 0
cnt_e = 0
cnt_error = 0
cnt_private = 0

while True:
    try:
        str1, str2 = input().split('~')
        invalid_ip = validate_ip(str1)
        if invalid_ip > 0:
            cnt_error += 1
        elif invalid_ip == 0:
            invalid_mask = validate_mask(str2)
            if invalid_mask == 1:
                cnt_error += 1
            elif invalid_mask == 0:
                cnt_private += is_private(str1)
                categorize_ip = categorize(str1)
                if categorize_ip == 'A':
                    cnt_a += 1
                elif categorize_ip == 'B':
                    cnt_b += 1
                elif categorize_ip == 'C':
                    cnt_c += 1
                elif categorize_ip == 'D':
                    cnt_d += 1
                elif categorize_ip == 'E':
                    cnt_e += 1
    except EOFError:
        break

print(cnt_a, cnt_b, cnt_c, cnt_d, cnt_e, cnt_error, cnt_private)


编辑于 2021-03-30 15:48:35 回复(0)

Python3 一种易懂的解题方法。

ans = [0]*7

while True:
    try:
        m = input().split("~")
        m0 = m[0].split(".")    #ip 地址
        m1 = m[1].split(".")    #子网掩码
        
        #检查是否有“空”的格式错误, 例如192..0.2
        flag = False
        for i in m0 + m1:
            if i.isdigit() == False:
                ans[5] += 1 # type 5
                flag = True
                break
        if flag == True:
            continue
        
        #求子网掩码的二进制格式 = m2
        m2 =""
        for i in m1:
            temp = "{0:b}".format(int(i))   #二进制转换
            m2 += '0'*(8-len(temp)) + temp  #补全8bit
        
        #检查子网掩码格式
        count = 0
        for i in range(len(m2)-1):
            if m2[i] != m2[i+1]:
                count += 1
        if count != 1:     #==1 说明格式正确
            ans[5] += 1 # type 5
            count = 0
            continue
        
        #统计
        if int(m0[0]) >= 1 and int(m0[0]) <= 126:
            ans[0] += 1
        elif int(m0[0]) >= 128 and int(m0[0]) <= 191:
            ans[1] += 1
        elif int(m0[0]) >= 192 and int(m0[0]) <= 223:
            ans[2] += 1
        elif int(m0[0]) >= 224 and int(m0[0]) <= 239:
            ans[3] += 1
        elif int(m0[0]) >= 240 and int(m0[0]) <= 255:
            ans[4] += 1
        
        if int(m0[0]) == 10:
            ans[6] += 1
        elif int(m0[0]) == 172 and int(m0[1]) >= 16 and int(m0[1]) <= 31:
            ans[6] += 1
        elif int(m0[0]) == 192 and int(m0[1]) == 168:
            ans[6] += 1
    except:
        break

for i in range(len(ans)-1):
    print(ans[i],end=" ")
print(ans[-1],end="")



发表于 2021-03-07 03:17:07 回复(0)
A,B,C,D,E,ip_n,wrong_n=0,0,0,0,0,0,0
def is_mask(str):
    str_=str.split('.')
    str_1=bin(int(str_[0]))[2:].rjust(8,'0')+bin(int(str_[1]))[2:].rjust(8,'0')+bin(int(str_[2]))[2:].rjust(8,'0')+bin(int(str_[3]))[2:].rjust(8,'0')
    if len(str_1.rstrip('0'))==32:  #排除全是1的情况
        return 0
    for i in str_1.rstrip('0'):
        if i=='0':
            return 0
    return 1

while True:
    try:
        ip,mask=input().split('~')
        ip_=ip.split('.')
        if int(ip_[0]) in range(1,127)&nbs***bsp;int(ip_[0]) in range(128,256):
            flag=0
            for i in ip_[1:]:
                if not i:
                    wrong_n+=1
                    flag=1
                    break
                elif int(i) not in range(0,256):
                    wrong_n+=1
                    flag=1
                    break
            if flag==0:
                if int(ip_[0]) in range(1,127):
                    if is_mask(mask):
                        A+=1
                    else:
                        wrong_n+=1
                        continue
                if int(ip_[0]) in range(128,192):
                    if is_mask(mask):
                        B+=1
                    else:
                        wrong_n+=1
                        continue
                if int(ip_[0]) in range(192,224):
                    if is_mask(mask):
                        C+=1
                    else:
                        wrong_n+=1
                        continue
                if int(ip_[0]) in range(224,240):
                    if is_mask(mask):
                        D+=1
                    else:
                        wrong_n+=1
                        continue
                if int(ip_[0]) in range(240,256):
                    if is_mask(mask):
                        E+=1
                    else:
                        wrong_n+=1
                        continue
                if int(ip_[0])==10:
                    if is_mask(mask):
                        ip_n+=1
                    else:
                        wrong_n+=1
                        continue
                if int(ip_[0])==172:
                    if int(ip_[1]) in range(16,32):
                        if is_mask(mask):
                            ip_n+=1
                        else:
                            wrong_n+=1
                            continue
                if int(ip_[0])==192:
                    if int(ip_[2])== 168:
                        if is_mask(mask):
                            ip_n+=1
                        else:
                            wrong_n+=1
                            continue
        elif not is_mask(mask):
            wrong_n+=1
    except:
        break
print(str(A)+' '+str(B)+' '+str(C)+' '+str(D)+' '+str(E)+' '+str(wrong_n)+' '+str(ip_n))

这题有个最恶心的问题是:就算ip地址不属于A-E:但是ip地址后面的掩码如果是不合法的,仍然需要增加不合法的ip_掩码的个数,很容易理解错误!!!!
编辑于 2021-03-06 14:39:58 回复(0)
li=[0]*7
al1=['254','252','248','240','224','192','128','0']
def IP(ip):
    if len(ip)!=4 or '' in ip:
        return 0
    else:
        for i in range(4):
            if int(ip[i])<0 or int(ip[i])>255:
                return 0
        else:
            return 1

def MS(ms):
    if len(ms) != 4 or '' in ms:
        return 0
    else:
        if ms[0] == '255':
            if ms[1] == '255':
                if ms[2] == '255':
                    if ms[3] in al1:
                        return 1
                    else:
                        return 0
                elif ms[2] in al1 and ms[3] == '0':
                    return 1
                else:
                    return 0
            elif ms[1] in al1 and ms[2] == ms[3] == '0':
                return 1
            else:
                return 0
        elif ms[0] in al1 and ms[2] == ms[3] == ms[4] == '0':
            return 1
        else:
            return 0
while True:
    try:
        s = input().split('~')
        ip = s[0].split('.')
        ms = s[1].split('.')
        if IP(ip) and MS(ms):
            if 1<=int(ip[0])<=126 and 0<=int(ip[1])<=255 and 0<=int(ip[2])<=255 and 0<=int(ip[3])<=255:
                li[0]+=1
            if 128<=int(ip[0])<=191 and 0<=int(ip[1])<=255 and 0<=int(ip[2])<=255 and 0<=int(ip[3])<=255:
                li[1]+=1
            if 192<=int(ip[0])<=223 and 0<=int(ip[1])<=255 and 0<=int(ip[2])<=255 and 0<=int(ip[3])<=255:
                li[2]+=1
            if 224<=int(ip[0])<=239 and 0<=int(ip[1])<=255 and 0<=int(ip[2])<=255 and 0<=int(ip[3])<=255:
                li[3]+=1
            if 240<=int(ip[0])<=255 and 0<=int(ip[1])<=255 and 0<=int(ip[2])<=255 and 0<=int(ip[3])<=255:
                li[4]+=1
            if int(ip[0])==10 and 0<=int(ip[1])<=255 and 0<=int(ip[2])<=255 and 0<=int(ip[3])<=255:
                li[6]+=1
            if int(ip[0])==172 and 16<=int(ip[1])<=31 and 0<=int(ip[2])<=255 and 0<=int(ip[3])<=255:
                li[6]+=1
            if int(ip[0])==192 and int(ip[1])==168 and 0<=int(ip[2])<=255 and 0<=int(ip[3])<=255:
                li[6]+=1
        else:
            li[5]+=1
    except:
        break
print(' '.join(map(str,li)))
发表于 2021-02-28 21:42:56 回复(0)
import re
import sys


output = [0] * 7

def check_ip(ip):
    a, b, c, d = ip
    if 1 <= a <= 126:
        output[0] += 1
    elif 128 <= a <= 191:
        output[1] += 1
    elif 192 <= a <= 223:
        output[2] += 1
    elif 224 <= a <= 239:
        output[3] += 1
    elif 240 <= a <= 255:
        output[4] += 1
    if a == 10&nbs***bsp;(a==172 and 16<=b<=31)&nbs***bsp;(a==192 and b==168):
        output[6] += 1


def check_mask(mask):
    if sum(mask) in (0, 255*4):
        output[5] += 1
        return False
    a, b, c, d = mask
    if a < 128:
        output[5] += 1
        return False
    mask = bin(a*256**3 + b*256**2 + c*256 + d)
    temp = mask.split("0")
    temp = [_ for _ in temp if _]
    if len(temp) > 1:
        output[5] += 1
        return False
    return True


def format_data(s):
    if not re.match(r"^(\d+\.){3}\d+$", s):
        return False
    data = list(map(int, s.split(".")))
    if max(data) > 255:
        return False
    return data

for i in sys.stdin:
    ip, mask = i.split("~")
    ip, mask = format_data(ip), format_data(mask)
    if not ip&nbs***bsp;not mask:
        output[5] += 1
        continue
    if check_mask(mask):
        check_ip(ip)
        
print(" ".join(map(str, output)))

发表于 2020-12-14 18:23:47 回复(0)
用input完美gg,666
发表于 2020-11-16 20:04:58 回复(0)
a,b,c,d,e,wrong,pr=0,0,0,0,0,0,0
def legalmask(mask):
    n = int(mask)
    n1 = 0b11111111
    x = n ^ n1
    y = x + 1
    z = str(bin(y))[2:]
    if z.count("1") == 1:
        return True
    else:
        return False
def detectmask(mask):
    flag = True
    if len(mask) != 4:
        flag = False
    if mask[0] == '255' and mask[1] == '255' and mask[2] == '255' and mask[3] == '255':
        flag = False
    for n in mask:
        if not n.isdigit():
            flag = False
            break
        n = int(n)
        if n < 0&nbs***bsp;n > 255:
            flag = False
            break
    if mask[0] != '255':
        if mask[1] != '0'&nbs***bsp;mask[2] != '0'&nbs***bsp;mask[3] != '0':
            flag = False
        if not legalmask(mask[0]):
            flag = False
    else:
        if mask[1] != '255':
            if mask[2] != '0'&nbs***bsp;mask[3] != '0':
                flag = False
            if not legalmask(mask[1]):
                flag = False
        else:
            if mask[2] != '255':
                if mask[3] != '0':
                    flag = False
                if not legalmask(mask[2]):
                    flag = False
            else:
                if not legalmask(mask[3]):
                    flag = False
    return flag

def detectip(ip):
    iptype = 6
    ispr = 0
    if len(ip) != 4:
        iptype = 0
    for n in ip:
        if not n.isdigit():
            iptype = 0
            return [iptype,0]
        if int(n) < 0&nbs***bsp;int(n) >255:
            iptype = 0
            return [iptype,0]
    if int(ip[0]) > 0 and int(ip[0]) < 127:
        iptype = 1
    if int(ip[0]) >= 128 and int(ip[0]) < 192:
        iptype = 2
    if int(ip[0]) >= 192 and int(ip[0]) < 224:
        iptype = 3
    if int(ip[0]) >= 224 and int(ip[0]) < 240:
        iptype = 4
    if int(ip[0]) >= 240:
        iptype = 5

    if int(ip[0]) == 10:
        ispr = 1
    if int(ip[0]) == 172 and int(ip[1]) >= 16 and int(ip[1]) <= 31:
        ispr = 1
    if int(ip[0]) == 192 and int(ip[1]) == 168:
        ispr = 1

    return [iptype,ispr]

while True:
    try:
        n = input().split("~")
        mask = n[1].split(".")
        if not detectmask(mask):
            wrong += 1
            continue
        ip = n[0].split(".")
        if detectip(ip)[0] == 1:
            a += 1
        if detectip(ip)[0] == 2:
            b += 1
        if detectip(ip)[0] == 3:
            c += 1
        if detectip(ip)[0] == 4:
            d += 1
        if detectip(ip)[0] == 5:
            e += 1
        if detectip(ip)[0] == 0:
            wrong += 1
        if detectip(ip)[1] == 1:
            pr += 1
    except:
        break
print(str(a)+' '+str(b)+' '+str(c)+' '+str(d)+' '+str(e)+' '+str(wrong)+' '+str(pr))

发表于 2020-09-12 19:32:33 回复(0)
被这个题目折磨了好几个小时,太多坑了
最大的坑是自己没看清楚题目,如果一组数据不管是那一部分出错了,另一部分即使是正确的也会不算数。
def isIP(strr):
    A = 0
    B = 0
    C = 0
    D = 0
    E = 0
    fs = 0
    prip = 0
    IP = strr.split('.')
    if len(IP) == 4:
        for each in IP:
            if each.isnumeric() and 0 <= int(each) <= 255:
                continue
            else:
                if int(each) == 0:
                    return A, B, C, D, E, fs, prip
                else:
                    fs = 1
                    return A, B, C, D, E, fs, prip

        if int(IP[0]) == 0:
            return A, B, C, D, E, fs, prip

        if 126 >= int(IP[0]) >= 1:
            if int(IP[0]) == 10:
                prip = 1
            A = 1
            return A, B, C, D, E, fs, prip
        elif 191 >= int(IP[0]) >= 128:
            if int(IP[0]) == 172 and 16 < int(IP[1]) < 31:
                prip = 1
            B = 1
            return A, B, C, D, E, fs, prip
        elif 223 >= int(IP[0]) >= 192:
            if int(IP[0]) == 192 and int(IP[1]) == 168:
                prip = 1
            C = 1
            return A, B, C, D, E, fs, prip
        elif 239 >= int(IP[0]) >= 224:
            D = 1
            return A, B, C, D, E, fs, prip
        elif 255 >= int(IP[0]) >= 240:
            E = 1
            return A, B, C, D, E, fs, prip
        else:
            if int(IP[0]) == 127:
                return 0, 0, 0, 0, 0, 0, 0
    else:
        fs = 1
        return A, B, C, D, E, fs, prip


def isfsubnet(strr):
    A = 0
    B = 0
    C = 0
    D = 0
    E = 0
    fs = 0
    prip = 0
    IP = strr.split('.')
    subnet = ''
    if len(IP) == 4:
        f1 = '0' * 32
        f2 = '1' * 32
        for each in IP:
            if each.isnumeric() and 0 <= int(each) <= 255:
                continue
            else:
                fs = 1
                return 0, 0, 0, 0, 0, fs, 0
        for each in IP:
            subnet = subnet + str(bin(int(each)))[2:].zfill(8)
        if '01' in subnet:
            fs = 1
            return 0, 0, 0, 0, 0, fs, 0
        elif subnet == f1&nbs***bsp;subnet == f2:
            fs = 1
            return 0, 0, 0, 0, 0, fs, 0
        else:
            return A, B, C, D, E, fs, prip
    else:
        fs = 1
        return 0, 0, 0, 0, 0, fs, 0


result = [0, 0, 0, 0, 0, 0, 0]
while True:
    try:
        x = input()
        ip = x.split('~')
        IP = ip[0]
        subnet = ip[1]
        arr11 = isIP(IP)
        arr11 = list(arr11)
        arr22 = list(isfsubnet(subnet))
        if arr11[-2] == 1&nbs***bsp;arr22[-2] == 1:
            arr11 = [0, 0, 0, 0, 0, 1, 0]
            arr22 = [0, 0, 0, 0, 0, 0, 0]
        for i in range(len(arr22)):
            result[i] = result[i] + arr11[i] + arr22[i]
    except Exception as e: 
        break

print("{} {} {} {} {} {} {}".format(result[0], result[1], result[2], result[3], result[4], result[5], result[6]))


发表于 2020-09-10 14:36:57 回复(0)
为什么没人用正则啊
发表于 2020-08-20 21:27:25 回复(0)
# 判断掩码
def isMask(mask):
    nums = mask.split('.')
    if len(nums) != 4:
        return False
    mask_str = ''
    for num in nums:
        num = int(num)
        bin_num = bin(num)[2:]
        if len(bin_num) != 8:
            bin_num = '0' * (8 - len(bin_num)) + bin_num
        mask_str += bin_num
    index_one = -1
    index_zero = -1
    for i in range(len(mask_str)):
        if mask_str[i] == '1':
            index_one = i
        if mask_str[len(mask_str) - 1 - i] == '0':
            index_zero = len(mask_str) - 1 - i
    if index_one < index_zero and index_zero >= 0 and index_one >= 0:
        return True
    else:
        return False

# 判断ip类型
def ipType(ip):
    ips = ip.split('.')
    if len(ips) != 4:
        return 'error'
    if 1 <= int(ips[0]) <= 126 and 0 <= int(ips[1]) <= 255 and 0 <= int(ips[2]) <= 255 and 0 <= int(ips[3]) <= 255:
        return 'A'
    if 128 <= int(ips[0]) <= 191 and 0 <= int(ips[1]) <= 255 and 0 <= int(ips[2]) <= 255 and 0 <= int(ips[3]) <= 255:
        return 'B'
    if 192 <= int(ips[0]) <= 223 and 0 <= int(ips[1]) <= 255 and 0 <= int(ips[2]) <= 255 and 0 <= int(ips[3]) <= 255:
        return 'C'
    if 224 <= int(ips[0]) <= 239 and 0 <= int(ips[1]) <= 255 and 0 <= int(ips[2]) <= 255 and 0 <= int(ips[3]) <= 255:
        return 'D'
    if 240 <= int(ips[0]) <= 255 and 0 <= int(ips[1]) <= 255 and 0 <= int(ips[2]) <= 255 and 0 <= int(ips[3]) <= 255:
        return 'E'
    return ''

#判断私有
def isPrivate(ip):
    ips = ip.split('.')
    if len(ips) != 4:
        return False
    if int(ips[0]) == 10 and 0 <= int(ips[1]) <= 255 and 0 <= int(ips[2]) <= 255 and 0 <= int(ips[3]) <= 255:
        return True
    if int(ips[0]) == 172 and 16 <= int(ips[1]) <= 31 and 0 <= int(ips[2]) <= 255 and 0 <= int(ips[3]) <= 255:
        return True
    if int(ips[0]) == 192 and int(ips[1]) == 168 and 0 <= int(ips[2]) <= 255 and 0 <= int(ips[3]) <= 255:
        return True
    return False

ans_dict = {'A':0, 'B':0, 'C':0, 'D':0, 'E':0, 'error':0, 'private':0}
while True:
    try:
        input_str = input()
        ip, mask = input_str.split('~')
        if isMask(mask):
            ip_type = ipType(ip)
            if ip_type != '':
                ans_dict[ip_type] += 1
            if isPrivate(ip):
                ans_dict['private'] += 1
        else:
            ans_dict['error'] += 1
    except:
        break
print(ans_dict['A'], ans_dict['B'], ans_dict['C'], ans_dict['D'], ans_dict['E'], ans_dict['error'], ans_dict['private'])
发表于 2020-08-18 13:43:53 回复(0)
def checkyanma(yanma01str):
    if yanma01str[0]=='0'&nbs***bsp;yanma01str[-1]=='1':
        return False
    ing = 1
    for c in yanma01str:
        if c=='1' and ing==0:
            return False
        if c=='0':
            ing=0
    return True

def checkip(iplist):
    kind, si = 5, 0
    for num in iplist:
        if num<0&nbs***bsp;num>255:
            return kind, si
    if 1<=iplist[0]<=126: kind = 0
    elif 128<=iplist[0]<=191: kind = 1
    elif 192<=iplist[0]<=223: kind = 2
    elif 224<=iplist[0]<=239: kind = 3
    else: kind = 4
    if iplist[0]==10: si = 1
    elif iplist[0]==172 and 16<=iplist[1]<=31: si = 1
    elif iplist[0]==192 and iplist[1]==168: si = 1
    return kind, si

def solution(record):
    ans = [0,0,0,0,0,0,0]
    for _ in record:
        ipstr, yanmastr = _[0], _[1]
        iplist = list(map(int, [x for x in ipstr.split('.') if x]))
        yanmalist = list(map(int, [x for x in yanmastr.split('.') if x]))
        if len(iplist)!=4:
            ans[5] += 1
            continue
        
        if len(yanmalist)!=4:
            ans[5] += 1
            continue
        yanma01str = ''.join(list(map(lambda x:bin(x)[2:].rjust(8, '0'), yanmalist)))
        if not checkyanma(yanma01str):
            ans[5] += 1
            continue
        # 排除0和127开头
        if iplist[0]==0&nbs***bsp;iplist[0]==127: continue
        kind, si = checkip(iplist)
        ans[kind]+=1
        ans[-1]+=si
    return ' '.join(list(map(str, ans)))

import sys
while True:
    try:
        record = []
        #while True:
        for line in sys.stdin:
            # inputlist = sys.stdin.readline()
            # inputlist = input()
            # if inputlist=='':
             #     break
            record.append(list(line.split('~')))
        if record==[]:
            break
        else:
            print(solution(record))
    except:
        break

最坑的就是127的时候直接跳过,但掩码错了其实不能跳过,要错误加一的。
输入也不能用input,像这种没有制定输入多少行的要用for line in sys.stdin:


发表于 2020-08-18 11:42:07 回复(2)
import sys
#判断子网掩码是否存在非连续的1,(以下是所有连续1的情况)
lll=['254','252','248','240','224','192','128','0']#可用bin()函数求,如bin(248)得到:1111 1000
A, B, C, D, E, err, pri = 0,0,0,0,0,0,0
#检测IP是否有效
def check_ip(ip):
    if len(ip)!=4&nbs***bsp;"" in ip: return False
    else:
        for i in range(4):
            if int(ip[i])<0&nbs***bsp;int(ip[i])>255:
                return False
        return True        
def check_mask(ms):
    if len(ms)!=4:
        return  False
    if ms[0]=='255':
        if ms[1]=='255':
            if ms[2]=='255':
                if ms[3] in lll:
                    return True
                else:
                    return False
            elif ms[2] in lll and ms[3]=='0':
                return True
            else:
                return False
        elif ms[1] in lll and ms[2]==ms[3]=='0':
            return True
        else:
            return False
    elif ms[0] in lll and ms[2]==ms[3]==ms[4]=='0':
        return True
    else:
        return False
#测试用例,输入不符合上述情况的数,就终止,然后答应答案
while True:
    try:
        string=sys.stdin.readline().strip()
        if string=='':
            break
        list1=string.split('~')[0]  #IP地址分割
        list2=string.split('~')[1]  #子网掩码分割
        ip=list1.split('.')
        ms=list2.split('.')
        if check_mask(ms) and check_ip(ip):
            if 1<=int(ip[0])<=126:
                A+=1
            if 128<=int(ip[0])<=191:
                B+=1
            if 192<=int(ip[0])<=223:
                C+=1
            if 224<=int(ip[0])<=239:
                D+=1
            if 240<=int(ip[0])<=255:
                E+=1
            if int(ip[0])==10&nbs***bsp;(int(ip[0])==172 and 15<int(ip[1])<32)&nbs***bsp;(int(ip[0])==192 and int(ip[1])==168):
                pri+=1
        else:
            err+=1
    except:
        break
print(A,B,C,D,E,err,pri)



发表于 2020-08-14 21:14:43 回复(0)

问题信息

难度:
47条回答 90980浏览

热门推荐

通过挑战的用户

查看代码