题解 | 判断两个IP是否属于同一子网
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import sys
# 输入处理:'__.__.__.__' --> [__,__,__,__] >> 判断ip是否合法
# 输入处理:'__.__.__.__' --> '____' 32位二进制字符串 >> 判断子网掩码是否合法 and 进行AND运算,判断是否在同一子网
n,x,y = sys.stdin.read().split()
def ten_two(s):
"""10进制的'__.__.__.__'转换为长度为32的二进制字符串"""
lst_s = list(map(int,s.split('.')))
lst_s_2 = []
for ss in lst_s:
ss_2 = bin(ss)[2:]
if len(ss_2) < 8:
ss_2 = '0' * (8 - len(ss_2)) + ss_2
lst_s_2.append(ss_2)
return ''.join(lst_s_2)
def islegal(s):
"""判断是否0 <= __ <= 255,参数s是十进制的'__.__.__.__'字符串"""
lst_s = list(map(int,s.split('.')))
for ss in lst_s:
if 0 <= ss <= 255:
pass
else:
return False
return True
def net_islegal(s):
"""判断子网掩码是否合法"""
if islegal(s):
s_2 = ten_two(s)
i = 0
while s_2[i] == '1':
i += 1
if '1' in s_2[i+1:]:
return False
return True
else:
return False
if net_islegal(n) and islegal(x) and islegal(y):
n_2 = ten_two(n)
x_2 = ten_two(x)
y_2 = ten_two(y)
x_2_and = ''.join('1' if n_2[i] == '1' and x_2[i] == '1' else '0' for i in range(32))
y_2_and = ''.join('1' if n_2[i] == '1' and y_2[i] == '1' else '0' for i in range(32))
if x_2_and == y_2_and:
print('0')
else:
print('2')
else:
print('1')
出现的错误:
1.子网掩码需要两步验证:
1)0~255
2)'1' * x + '0' * (32-x)
2.ip验证只需要2)
3.字符串切片的结果仍是字符串,写判断时等号右边易写成数值,导致所有判断全部为False