题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import sys
def to_bin_8(in_dec):
out_bin = str(in_dec % 2)
for i in range(7):
in_dec = int(in_dec / 2)
out_bin = str(in_dec % 2) + out_bin
return out_bin
def to_dec(in_bin):
i = 1
out_dec = 0
for j in range(len(in_bin) - 1, -1, -1):
out_dec += int(in_bin[j]) * i
i *= 2
return out_dec
def addr_to_num(in_addr):
bin_addr = ""
for part in in_addr.split("."):
bin_addr += to_bin_8(int(part))
return to_dec(bin_addr)
a = 0
b = 0
c = 0
d = 0
e = 0
invalid = 0
private = 0
private_bounds = [
(addr_to_num("10.0.0.0"), addr_to_num("10.255.255.255")),
(addr_to_num("172.16.0.0"), addr_to_num("172.31.255.255")),
(addr_to_num("192.168.0.0"), addr_to_num("192.168.255.255"))
]
a_bounds = (addr_to_num("1.0.0.0"), addr_to_num("126.255.255.255"))
b_bounds = (addr_to_num("128.0.0.0"), addr_to_num("191.255.255.255"))
c_bounds = (addr_to_num("192.0.0.0"), addr_to_num("223.255.255.255"))
d_bounds = (addr_to_num("224.0.0.0"), addr_to_num("239.255.255.255"))
e_bounds = (addr_to_num("240.0.0.0"), addr_to_num("255.255.255.255"))
for line in sys.stdin:
addr, mask = line.split("~")
try:
pass_this = False
if addr.split(".")[0] == "0" or addr.split(".")[0] == "127":
continue
bin_mask = ""
for part in mask.split("."):
bin_mask += to_bin_8(int(part))
if bin_mask[0] == "0" or bin_mask[-1] == "1":
invalid += 1
continue
allow_one = True
for i in bin_mask:
if i == "0" and allow_one:
allow_one = False
if i == "1" and not allow_one:
pass_this = True
break
if pass_this:
invalid += 1
continue
num_mask = to_dec(bin_mask)
num_addr = addr_to_num(addr)
masked_addr = num_addr & num_mask
if (masked_addr >= private_bounds[0][0] and masked_addr <= private_bounds[0][1]) \
or (masked_addr >= private_bounds[1][0] and masked_addr <= private_bounds[1][1]) \
or (masked_addr >= private_bounds[2][0] and masked_addr <= private_bounds[2][1]):
private += 1
if masked_addr >= a_bounds[0] and masked_addr <= a_bounds[1]:
a += 1
elif masked_addr >= b_bounds[0] and masked_addr <= b_bounds[1]:
b += 1
elif masked_addr >= c_bounds[0] and masked_addr <= c_bounds[1]:
c += 1
elif masked_addr >= d_bounds[0] and masked_addr <= d_bounds[1]:
d += 1
elif masked_addr >= e_bounds[0] and masked_addr <= e_bounds[1]:
e += 1
except:
invalid += 1
continue
print("{} {} {} {} {} {} {}".format(a, b, c, d, e, invalid, private))
查看18道真题和解析