题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
def ip_check(_ip_list): # 无效ip跳过归类 if len(_ip_list[0])==0: return True if int(_ip_list[0]) == 127 or int(_ip_list[0]) == 0: # print('无效ip') return False else: return True def illegal_ip_check(_ip_list): # 非法ip计入统计 for i in _ip_list: if len(i) == 0: # print('非法ip') return True # print('有效法ip') return False def illeagal_mask_check(_ip_list): # 子网掩码非法计入统计 temp_list = [] for i in _ip_list: new_str=str(bin(int(i)))[2:] new_str =new_str.rjust(8) new_str=new_str.replace(' ','0') # print(new_str) # print(str(bin(int(i)))[2:]) temp_list.append(new_str) temp_str = ''.join(temp_list) # print(temp_str) if temp_str[0] == '0': # print('无效掩码') return True if len(temp_str) == temp_str.count('1'): # print('无效掩码') return True elif temp_str[0] == '1': for i in range(len(temp_str)): if temp_str[i] == '0': for k in range(i, len(temp_str)): while temp_str[k] != '0': # print('无效掩码') return True # print('有效掩码') return False return False def abcde_type(_ip_list): num = int(_ip_list[0]) if num >=1 and num <=126: return "A" if num >=128 and num <=191: return "B" if num >=192 and num <=223: return "C" if num >=224 and num <=239: return "D" if num >=240 and num <=255: return "E" def p_type(_ip_list): num1 = int(_ip_list[0]) num2 = int(_ip_list[1]) if num1 ==10: # print('私有') return True condition1 = num2>=16 and num2<31 if num1==172 and condition1: # print('私有') return True if num1 ==192 and num2==168: # print('私有') return True output_dict = { "A": 0, "B":0, "C":0, "D":0, "E":0, "Wrong":0, "P":0 } while True: try: # print('------------') input_str = input() ip, mask = input_str.split('~') ip_list = ip.split('.') mask_list = mask.split('.') if ip_check(ip_list): if illegal_ip_check(ip_list) or illeagal_mask_check(mask_list): output_dict['Wrong'] +=1 # print('Wrong') continue # print(abcde_type(ip_list)) output_dict[abcde_type(ip_list)] +=1 if p_type(ip_list): output_dict['P'] +=1 else: continue except: break # print(output_dict) for i in output_dict.values(): print(i,end=' ')
#华为机试#