题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
测试狗平常不用&符都忘记了,无脑转换
注意坑:
- 掩码要校验0-255和转换后前半分是1后半部分是0的情况
- bin函数转换后取消0b并且左侧补0到8位
- 注意if逻辑,他那个0,1,2还不按顺序描述 =================
下次更新使用&符号的做法
import re
def transfer_ip(ip):
ip_list = [bin(int(x))[2:].rjust(8,'0') for x in ip.split('.')]
return ''.join(ip_list)
def transfer_mask(mask):
mask_list = [bin(int(x))[2:].rjust(8, '0') for x in mask.split('.') if 1 <= int(x) <= 255]
return ''.join(mask_list)
def valid_ip(ip):
ip_list = [int(x) for x in ip.split('.') if 0 <= int(x) <= 255]
if len(ip_list) == 4:
return True
return False
def valid_mask(mask):
mask_list = [bin(int(x))[2:].rjust(8, '0') for x in mask.split('.') if 0 <= int(x) <= 255]
mask_str = ''.join(mask_list)
pattern = re.compile('^[1]{1,32}[0]{1,32}$')
if pattern.search(mask_str) and len(mask_list) == 4:
return True
return False
def get_ip_and_mask(ip_str, mask_str):
and_ip = ''
for x,y in zip(ip_str, mask_str):
if x == '1' and y == '1':
and_ip += '1'
else:
and_ip += '0'
return and_ip
while True:
try:
mask, ip1, ip2 = input(),input(),input()
if valid_ip(ip1) and valid_ip(ip2) and valid_mask(mask):
t_ip1, t_ip2, t_mask = transfer_ip(ip1), transfer_ip(ip2), transfer_mask(mask)
and_ip1 = get_ip_and_mask(t_ip1, t_mask)
and_ip2 = get_ip_and_mask(t_ip2, t_mask)
if and_ip1 == and_ip2:
print(0)
else:
print(2)
else:
print(1)
except EOFError:
break