HJ18 识别有效的IP地址和掩码并进行分类统计
题目
HJ18 识别有效的IP地址和掩码并进行分类统计
思路
先将十进制带点的ip地址转成二进制序列(没有点),再直接比较。
rjust右对齐,左边补充0.
re.search(“/./.”, str) 找str中的"…", 找到第一个匹配的返回一个object,找不到返回None。
代码
import sys
import re
def get_bin(input):
'''
input: 10 base with dot
output: 01 base no bot
'''
str_ = ""
for e in input.split("."):
str_ += bin(int(e))[2:].rjust(8, "0")
return str_
A,B,C,D,E,EIM,P = 0, 0, 0, 0, 0, 0, 0
for line in sys.stdin:
a = line.split()[0]
ip, m = a.split("~")
if m == "0.0.0.0" or m == "255.255.255.255":
EIM += 1
continue
# if ip.split(".")[0] in ("0", "127"): # 如果写成ip.split(".")[0]=="0" or ip.split(".")[0]=="127" 不对 因为== 和 or 同等级会左右依次比较
# continue
if (ip.split(".")[0]=="0") or (ip.split(".")[0]=="127"): # 加括号可以
continue
if re.search("01", get_bin(m)):
EIM += 1
continue
bin_ip = get_bin(ip)
if re.search(r"/./.", ip):
EIM += 1
elif get_bin("1.0.0.0") <= bin_ip <= get_bin("126.255.255.255"):
A += 1
if get_bin("10.0.0.0") <= bin_ip <= get_bin("10.255.255.255"):
P += 1
elif get_bin("128.0.0.0") <= bin_ip <= get_bin("191.255.255.255"):
B += 1
if get_bin("172.16.0.0") <= bin_ip <= get_bin("172.31.255.255"):
P += 1
elif get_bin("192.0.0.0") <= bin_ip <= get_bin("223.255.255.255"):
C += 1
if get_bin("192.168.0.0") <= bin_ip <= get_bin("192.168.255.255"):
P += 1
elif get_bin("224.0.0.0") <= bin_ip <= get_bin("239.255.255.255"):
D += 1
elif get_bin("240.0.0.0") <= bin_ip <= get_bin("255.255.255.255"):
E += 1
print("{} {} {} {} {} {} {}".format(A,B,C,D,E,EIM,P))
参考
【华为机试Python3题解】HJ18识别有效的IP地址和掩码并进行分类统计