题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import sys
import re
pattern = r'^([0-9]{1,3}.){3}([0-9]{1,3}){1}$'
DATA = []
for line in sys.stdin:
DATA.append(line.strip()) # 使用strip()删除每行末尾的换行符
A, B, C, D, E, F, L = 0, 0, 0, 0, 0, 0, 0
for data in DATA:
data = data.split('~')
ip = re.match(pattern, data[0])
dom = re.match(pattern, data[1])
# 判断是否匹配不合法
if ip is None or dom is None:
F += 1
print(ip, dom)
continue
# 判断是否数值不合法
ip, dom = ip.group(), dom.group()
ip, dom = ip.split('.'), dom.split('.')
ip = [int(x) for x in ip]
dom = [int(x) for x in dom]
def catch_256 (arr):
for i in range(4):
if arr[i]>255:
return True
return False
if catch_256(ip) or catch_256(dom):
F+=1
# print(ip, dom)
continue
# 不计数
if ip[0] == 0 or ip[0] == 127:
continue
# 判断掩码是否合法
dom_x = 0
for d in dom:
dom_x = dom_x * 256 + d
dom_bin = bin(dom_x)
dom_re = re.match(r'^0b1+0+$', dom_bin)
if dom_re is None:
F += 1
# print(ip, dom)
continue
# 判断是否是私网
if ip[0] == 10:
L += 1
# continue
elif ip[0] == 172 and ip[1] >= 16 and ip[1] <= 31:
L += 1
# continue
elif ip[0] == 192 and ip[1] == 168:
L+= 1
# continue
if ip[0] > 0 and ip[0] <= 126:
A += 1
# print('A:', ip, dom)
continue
elif ip[0] >= 128 and ip[0] <= 191:
B += 1
continue
elif ip[0] >= 192 and ip[0] <= 223:
C += 1
continue
elif ip[0] >= 224 and ip[0] <= 239:
D += 1
continue
elif ip[0] >= 240 and ip[0] <= 255:
E += 1
continue
print(A, B, C, D, E, F, L )
