题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
大佬函数名掉了,补上
def int2bin(ipt):
lst = list(map(int, ipt.split('.')))
res = ''
for i in lst:
a = bin(i)[2:]
b = '0' * (8 - len(a)) + str(a)
res += b
return res
def check_ip(ip):
ip_lst = list(map(int, ip.split('.')))
if len(ip_lst) != 4 or '' in ip_lst:
return False
for i in ip_lst:
if not 0 <= i <= 255:
return False
return True
def check_mask(mask):
if not check_ip(mask):
return False
res = int2bin(mask)
if res.find('0') == res.rfind('1') + 1:
return True
return False
def check_subnet(ip, mask):
ip_lst = list(map(int, ip.split('.')))
mask_lst = list(map(int, mask.split('.')))
subnet = []
for i in range(4):
subnet.append(ip_lst[i] & mask_lst[i])
return subnet
while True:
try:
mask1 = input()
ip1 = input()
ip2 = input()
if check_mask(mask1) and check_ip(ip1) and check_ip(ip2):
if check_subnet(ip1, mask1) == check_subnet(ip2, mask1):
print('0')
else:
print('2')
else:
print('1')
except:
break