题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
这里的主要难点是子网掩码的判断,并不是只有255和0,需要转换成二进制
import sys
def is_valid_ip(lst):
try:
if any(i == '' for i in lst):
return False
return all(0 <= int(i) <= 255 for i in lst) and len(lst) == 4
except ValueError:
return False
def is_valid_sm(lst):
try:
if any(i == '' for i in lst) or len(lst) != 4 :
return False
decimal_value = (int(lst[0]) << 24) + (int(lst[1]) << 16) + (int(lst[2]) << 8) + int(lst[3])
_str= '{:032b}'.format(decimal_value)
if '1' not in _str or '0' not in _str or '01' in _str:
return False
return True
except ValueError:
return False
res = {
'A': 0,
'B': 0,
'C': 0,
'D': 0,
'E': 0,
'F': 0,
'G': 0,
}
try:
while True:
ip, sm = input().split('~')
ip_list = list(map(str, ip.split('.')))
sm_list = list(map(str, sm.split('.')))
if ip_list[0] in [0, 127,'0','127']:
continue
if not is_valid_ip(ip_list) or not is_valid_sm(sm_list):
res['F'] += 1
#print(f'{ip_list} {sm_list}')
continue
ip_list = list(map(int, ip_list))
if ip_list[0] < 128:
res['A'] += 1
if ip_list[0] == 10 or (ip_list[0] == 172 and 31 >= ip_list[1] >= 16):
res['G'] += 1
elif ip_list[0] < 192:
res['B'] += 1
elif ip_list[0] < 224:
res['C'] += 1
if ip_list[0] == 192 and ip_list[1] == 168:
res['G'] += 1
elif ip_list[0] < 240:
res['D'] += 1
else:
res['E'] += 1
except EOFError:
val = list(map(str, res.values()))
print(' '.join(val))
#在找工作求抱抱#