华为机试HJ18 识别有效的IP地址和掩码

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

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

python3 解法供参考

def checkvalid(ip, ym):
    # 若ip错误,则掩码无需判断
    ip1 = filter(None, ip.split('.'))
    ip2 = [int(x) for x in ip1]
    if len(ip2) < 4:
        return False
    else:
        # 子网掩码去掉分隔符'.'
        ym1 = list(map(int, ym.split('.')))
        # 二进制转换和高位补0
        ym2 = ''.join(['{:08b}'.format(i) for i in ym1])
        if ym2.find('0') == -1 or ym2.find('1') == -1 or ym2.find('0') != ym2.rfind('1') + 1:
            return False
        return True

def publicip(ip):
    ipn = [int(n) for n in ip.split('.')]
    if 1 <= ipn[0] <= 126:
        return 'a'
    elif 128 <= ipn[0] <= 191:
        return 'b'
    elif 192 <= ipn[0] <= 223:
        return 'c'
    elif 224 <= ipn[0] <= 239:
        return 'd'
    elif 240 <= ipn[0] <= 255:
        return 'e'
    else:
        return 'ignore'

def privateip(ip):
    ipn = [int(n) for n in ip.split('.')]
    if (ipn[0] == 10) or (ipn[0] == 172 and (16 <= ipn[1] <= 31)) or (ipn[0] == 192 and ipn[1] == 168):
        return True
    return False

def resprint(ip, ym, classdic):
    if checkvalid(ip, ym):
        classdic[publicip(ip)] += 1
        if privateip(ip):
            classdic['private'] += 1
    else:
        classdic['wrong'] += 1
    return classdic


import sys
from collections import defaultdict
def main():
    classdic = defaultdict(int)
    for line in sys.stdin:
        ip, ym = line.split('~')
        resprint(ip, ym, classdic)
    res = []
    for key in ['a', 'b', 'c', 'd', 'e', 'wrong', 'private']:
        res.append(classdic[key])
    print(' '.join(res))

main()
全部评论
append添加元素需要转换为str类型
1 回复 分享
发布于 2021-02-20 16:45
如果IP的后面几位有大于255的不能把它识别成错误地址
1 回复 分享
发布于 2021-09-16 17:18
喜欢!看的明明白白
点赞 回复 分享
发布于 2021-07-21 01:08
main函数里面直接join报错了,改成了: def main(): rres = '' classdic = defaultdict(int) for line in sys.stdin: ip, ym = line.split('~') resprint(ip, ym, classdic) res = [] for key in ['a', 'b', 'c', 'd', 'e', 'wrong', 'private']: res.append(classdic[key]) res_len = len(res) j = 0 for k in res: j += 1 rres += str(k) if(j==res_len):pass else:rres += ' ' print(rres) 然后运行只通过8/10
点赞 回复 分享
发布于 2022-05-10 10:39
127.*.*.*需要丢掉不计数
点赞 回复 分享
发布于 2022-11-13 13:20 四川
def ignoreip(ip): ipn = [int(n) for n in ip.split('.')] if ipn[0] == 0 or ipn[0] == 127: return True return False def resprint(ip,ym,classdic): if checkvalid(ip,ym): classdic[publicip(ip)] += 1 if privateip(ip): classdic['private'] += 1 else : if ignoreip(ip): classdic['wrong'] += 0 else: classdic['wrong'] += 1 return classdic 上面部分代码以及res.append(str(classdic[key]))更改之后就可以完全通过用例了。
点赞 回复 分享
发布于 2023-04-09 23:48 广东

相关推荐

小红书 后端开发 总包n+8w+期权
点赞 评论 收藏
分享
11 9 评论
分享
牛客网
牛客企业服务