牛客识别有效的掩码并且分类统计(python)

import sys

ips = []
while True:
    line = sys.stdin.readline().strip()
    if line == '':
        break
    ips.append((line.split('~')[0], line.split('~')[1]))
A = B = C = D = E = 0
error_ip = 0
key = 0
for ip in ips:
    ip_l = ip[0].split('.')
    # 忽略ip
    if ip_l[0] == '0' or ip_l[0] == '127':
        continue
    # 验证ip非法
    if '' in ip_l:
        error_ip += 1
        continue
    else:
        if any([int(i) < 0 or int(i) > 255 for i in ip_l]):
            error_ip += 1
            continue
    # 验证子网掩码是否非法
    ip_k = ''
    for j in ip[1].split('.'):
        b = str(bin(int(j))).lstrip('0b')
        if len(b) < 8:
            b = '0' * (8 - len(b)) + b
        ip_k += b
    if ip_k.lstrip('1').lstrip('0') != '' or all([i == '1' for i in ip_k]) or all([i == '0' for i in ip_k]):
        error_ip += 1
        continue
    # 分类
    if int(ip_l[0]) >= 1 and int(ip_l[0]) <= 126:
        A += 1
    elif int(ip_l[0]) >= 128 and int(ip_l[0]) <= 191:
        B += 1
    elif int(ip_l[0]) >= 192 and int(ip_l[0]) <= 223:
        C += 1
    elif int(ip_l[0]) >= 224 and int(ip_l[0]) <= 239:
        D += 1
    elif int(ip_l[0]) >= 240 and int(ip_l[0]) <= 255:
        E += 1
    # 私有ip
    if ip_l[0] == '10' or (ip_l[0] == '172' and int(ip_l[1]) in range(16, 33)) \
            or (ip_l[0] == '192' and int(ip_l[1]) == 168):
        key += 1
print(A, B, C, D, E, error_ip, key)

原题链接:

https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682?tpId=37&tqId=21240&rp=1&ru=%2Fexam%2Foj%2Fta&qru=%2Fexam%2Foj%2Fta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=

你可能感兴趣的:(数据结构,python,算法)