题解 | #识别有效的IP地址和掩码并进行分类统计#

识别有效的IP地址和掩码并进行分类统计

http://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682

网络编译环境还是和本地不一样的,如果陷入死循环,完全看不出来错在哪里。
有两点建议:
1、先写好测试用例。
2、局部调试代码,这种写了两个函数的,应该每个函数先调试通,即所有的用例通过,再进行总的调试。
'''
10.254.254.254255.255.255.254
1.0.0.0
255.0.0.0
1.0.0.0255.255.255.32
128.0.0.0
255.255.255.254
191.255.255.255.255255.255.255.254
192.0.0.0.0
255.255.255.254
223.255.255.255255.255.255.254
224.0.0.0.0
255.255.255.254
239.255.255.255255.255.255.254
240.0.0.0
255.255.255.254
255.255.255.255~255.255.255.254
'''

def judge_ip(t):
ip_type, is_private = None, False
ip_flag = -1
#print('t的长度为', len(t))
if len(t) != 4:
return 'error', is_private
try:
t[0] = int(t[0])
if t[0] >= 1 and t[0] <= 126:
ip_type = 'A'
#print('it is A')
if t[0] == 10:
is_private = True
elif t[0] >= 128 and t[0] <= 191:
ip_type = 'B'
if t[0] == 172 and t[1]>=16 and t[1]<=31:
is_private = True
elif t[0] >= 192 and t[0] <= 223:
ip_type = 'C'
if t[0] == 192 and t[1]==168:
is_private = True
elif t[0] >= 224 and t[0] <= 239:
ip_type = 'D'
elif t[0] >= 240 and t[0] <= 255:
ip_type = 'E'
elif t[0] == 0 or t[0] == 127:
return 'ignore', is_private
else:
return 'error', is_private
for i in t[1:]:
if i >= 0 and i <= 255:
ip_flag = -ip_flag
#print('ip_flag is ', ip_flag)
if ip_flag == 1:
return ip_type, is_private
else:
return 'error', is_private
except:
return 'error', is_private

def judge_mask(t):
mask_set = [254, 252, 248, 240, 224, 192, 128]
#print('mask length is', len(t))
if len(t) != 4:
return False
i = 0
while i < 3:
if t[i] == 255:
#print('i is',i)
i += 1
continue
elif t[i] in mask_set and sum(t[i+1:]) == 0:
#print(t[i+1:])
return True
elif t[i] in mask_set and sum(t[i+1:]) != 0:
return False
elif t[i] not in mask_set:
break
i += 1
if i==3 and t[i] in mask_set:
return True
elif i>0 and sum(t[i:]) == 0:
return True
else:
return False

a_count,b_count,c_count,d_count,e_count,error_count,private_count = 0,0,0,0,0,0,0

d = {
'A': 0,
'B': 0,
'C': 0,
'D': 0,
'E': 0,
'error': 0,
'private': 0,
}
while True:
try:
s = input()
if len(s) == 0:
break
#print(s)
t = s.split('~')
new_ip = []
new_mask = []
try:
for i in t[0].split('.'):
i = int(i)
new_ip.append(i)
for i in t[1].split('.'):
i = int(i)
new_mask.append(i)
except:
pass
#print('准备判断IP')
iptype, is_private = judge_ip(new_ip)
#print(iptype, is_private)
is_mask = judge_mask(new_mask)
#print('是否为掩码', is_mask)
if iptype == 'ignore'and is_mask:
#print('is here2')
continue
if not is_mask:
#print('is here3')
d['error'] += 1
else:
d[iptype] += 1
if is_private:
d['private'] += 1
#print('is here1')
#print('is here4')
continue
except:
break
print(d['A'], d['B'], d['C'], d['D'], d['E'], d['error'], d['private'])

全部评论

相关推荐

头像
09-05 10:14
已编辑
门头沟学院 Java
赫一鸣:我昨天投的,今天就oc了,也没和我说要面试笔试啊?不说了这单要超时了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务