题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
L = [0] * 7 # result: A-E:0-4 Error:5 Private:6
def isip(lst): # 基础: 判断是否为ip 并成为ip列表 [d,d,d,d]
if len(lst) != 4 or '' in lst:
return 0
for i in lst:
if int(i) < 0 or int(i) > 255:
return 0
return 1
def ismask(lst):
if isip(lst):
lst01 = []
for i in lst:
lst01.append(bin(int(i))[2:].zfill(8))
str01 = ''.join(lst01)
t1 = abs(str01.rfind('1')) # 避免全0无法排查
t2 = str01.find('0')
if t1 + 1 == t2:
return 1
else:
return 0
else:
return 0
def Ip_classification(lst): # 主要
f = int(lst[0])
if 0 < f <= 126: # A
L[0] += 1
elif 128 <= f <= 191: # B
L[1] += 1
elif 192 <= f <= 223: # C
L[2] += 1
elif 224 <= f <= 239: # D
L[3] += 1
elif 240 <= f <= 255: # E
L[4] += 1
def isprivate(lst): # 基础
f = int(lst[0])
if f == 10: return 1
if f == 172 and 16 <= int(lst[1]) <= 31: return 1
if f == 192 and int(lst[1]) == 168:
return 1
else:
return 0
def isaddprivate(lst): # 主要
if isprivate(lst):
L[6] += 1
if __name__ == '__main__':
while True:
try:
ip, mask = input().split('~')
except:
break
ip_lst = ip.split('.') # [d,d,d,d]
mask_lst = mask.split('.')
if ip_lst[0] == '0' or ip_lst[0] =='127':
continue # ip 不分类就不再考虑掩码问题
r1 = isip(ip_lst)
r2 = ismask(mask_lst)
if r1 ==1 and r2 ==1: # 都合法
isaddprivate(ip_lst)
Ip_classification(ip_lst)
else:
L[5] += 1
for i in L:
print(i,end=' ')
vivo公司福利 698人发布