HW.识别有效的IP地址和掩码并进行分类统计

HW.识别有效的IP地址和掩码并进行分类统计_第1张图片
HW.识别有效的IP地址和掩码并进行分类统计_第2张图片

import sys
#只有当Ip和记录都有效时记录才算
#Judge valid Ip
def valid_ip(ip):
    ip = ip.split(".")
    if len(ip) != 4:
        return False
    for item in ip:
        if not item.isdigit():
            return False
        if not (0 <=int(item) <= 255):
            return False
    return True

def valid_mask(mask):
    #Judge valid mask
    if not valid_ip(mask):
        return False
    mask = mask.split(".")
    if len(mask) != 4:
        return False
    for item in mask:
        if not item.isdigit():
            return False

    str_bin = ""
    for item in mask:
        str_bin += (8-len(bin(int(item))[2:])) *"0" +bin(int(item))[2:]
    if str_bin[0] != "1":
        return False

    appear_O = False
    for i in range(len(str_bin)):
        if str_bin[i] == "0":
            appear_O = True
        if str_bin[i] == "1" and appear_O:
            return False
    return True and appear_O


ip_array = []
mask_array = []
countA, countB, countC, countD,countE, wa_ip_mask, private_ip = 0, 0, 0, 0, 0, 0, 0
while True:
    line = sys.stdin.readline().strip()
    if line == "":
        break
    ip, mask =  line.strip().split("~")
    if valid_ip(ip) and valid_mask(mask):
        ip_array.append(ip)
        mask_array.append(mask)
    else:
        wa_ip_mask += 1
for mask in mask_array:
    if not valid_mask(mask):
        wa_ip_mask += 1

for ip in ip_array:
    first, second = int(ip.split(".")[0]),int(ip.split(".")[1])
    if 1 <= first < 127:
        countA += 1
        if first == 10:
            private_ip +=1
    if 128 <= first < 192:
        countB += 1
        if first == 172 and 16 <= second < 32:
            private_ip += 1
    if 192 <= first < 224:
        countC += 1
        if first == 192 and second == 168:
            private_ip += 1
    if 224 <= first < 240:
        countD += 1
    if 240 <= first < 256:
        countE +=1

print(" ".join(map(str, [ countA, countB, countC, countD,countE, wa_ip_mask, private_ip])))


你可能感兴趣的:(LeetCode)