分类判 | HJ18 识别有效的IP地址和掩码并进行分类统计
ip_lst = [] mask_lst = [] res = [0]*7 def is_valid(addr, mask=False): if mask and (addr == '255.255.255.255' or addr == '0.0.0.0'): return False bin_addr = '' segs = addr.split('.') for i in range(len(segs)): if not segs[i]: return False segs[i] = int(segs[i]) if segs[i] < 0 or segs[i] > 255: return False if mask: bin_addr += '{:0>8}'.format(bin(segs[i])[2:]) if bin_addr: inx_0 = bin_addr.find('0') inx_1 = bin_addr.rfind('1') if inx_0 - inx_1 == 1: return True else: return False return True while True: try: ip, mask = input().split('~') segs = list(map(int, ip.split('.'))) # 跳过0.*.*.*和127.*.*.*类地址 if segs[0] == 0 or segs[0] == 127: continue if not is_valid(ip) or not is_valid(mask, True): res[-2] += 1 else: # 判断A类地址和私网1 if 1 <= segs[0] <= 126: if segs[0] == 10: res[-1] += 1 res[0] += 1 # 判断B类地址和私网2 elif 128 <= segs[0] <= 191: if segs[0] == 172 and (16 <= segs[1] <= 31): res[-1] += 1 res[1] += 1 # 判断C类地址和私网3 elif 192 <= segs[0] <= 223: if segs[0] == 192 and segs[1] == 168: res[-1] += 1 res[2] += 1 # 判断D类地址 elif 224 <= segs[0] <= 239: res[3] += 1 # 判断E类地址 elif 240 <= segs[0] <= 255: res[4] += 1 except: break print(' '.join(map(str, res)))
用时:40min
注意:0.*.*.*和127.*.*.*类地址不参与判断,要最先剔除
华为笔试刷题 文章被收录于专栏
高质量题: 1~40:HJ16,HJ22,HJ24,HJ26,HJ27,HJ28,HJ35,HJ37,HJ39; 40~80:HJ41,HJ42,HJ43,HJ44,HJ48,HJ50,HJ52,HJ53,HJ57,HJ61,HJ63,HJ64,HJ70,HJ71,HJ74,HJ77; 80~108:HJ82,HJ85,HJ88,HJ89,HJ93,HJ95,HJ98,HJ103,HJ107