题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import sys res = [0]*7 def func1(ip): # a-e 0-4 if 1 <= ip[0] <= 126: res[0] += 1 elif 128 <= ip[0] <= 191: res[1] += 1 elif 192 <= ip[0] <= 223: res[2] += 1 elif 224 <= ip[0] <= 239: res[3] += 1 elif 240 <= ip[0] <= 255: res[4] += 1 def func2(ip):# 不合法 if ip[0] == 10 or ip[0] == 127 or ip[0] == 192 and ip[1] == 168: res[6] += 1 def func3(ip): return ip[0] == 0 or ip[0] == 127 def func4(ip): # 掩码 val = (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3] val = bin(val)[2:] index_0 = val.find('0') index_1 = val.rfind('1') if index_0 == -1 or index_1 == -1 or index_0 - index_1 != 1: res[5] += 1 return False return True def func5(line): ip, msk = line.split('~') ip = [int(x) for x in filter(None, ip.split('.'))] msk = [int(x) for x in filter(None, msk.split('.'))] if len(ip) < 4 or len(msk) < 4: res[5] += 1 return if func3(msk) or func3(ip): return if func4(msk): func1(ip) func2(ip) for line in sys.stdin: # 读取每一行输入 func5(line) print(*res)