题解 | #验证IP地址#

验证IP地址

https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 验证IP地址
# @param IP string字符串 一个IP地址字符串
# @return string字符串
#
class Solution:
    def solve(self , IP: str) -> str:
        # IPv6
        if '.' in IP:
            list1=IP.split('.')
            # (1)用0开头不行
            count1=0
            for i in list1:
                if i.startswith('0'):
                    return 'Neither'
                else:
                    count1=count1+1
            # (2)4个十进制数,范围均为0-255
            count2=0
            for i in list1:
                if i<'0' or i>'255':
                    return 'Neither'
                else:
                    count2=count2+1
            if count2==len(list1) and count1==len(list1):
                return "IPv4"
            else:
                return 'Neither'
        # IPv6
        elif ':' in IP:
            list2=IP.split(':')
            # (1)地址不等于八组
            if len(list2)!=8:
                return 'Neither'
            for i in list2:
                # (2)有空组
                if i=='':
                    return 'Neither'
                # (3)某个组的长度大于4
                if len(i)>4:
                    return 'Neither'
                # (4)包含不等于(a~f/A~F)的字母
                for j in i:
                    if (j>='g' and j<='z') or (j>='G' and j<='Z'):
                        return 'Neither' 
            return "IPv6"





全部评论

相关推荐

程序员小白条:你不是有一段实习了吗,现在找中大厂实习?过段时间要秋招了
我的简历长这样
点赞 评论 收藏
分享
05-23 19:02
吉林大学 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
今天 12:04
毕业生招你惹你了,问一个发薪日来一句别看网上乱七八糟的你看哪个工作没有固定发薪日扭头就取消了面试就问了一句公司都是这个态度吗还搞上人身攻击了...
程序员小白条:呃呃呃,都还没面试,我都不会问这么细,何况通不通过,去不去都另说,你没实力和学历的话,在外面就这样,说实话没直接已读不回就不错了,浪费时间基本上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务