题解 | #验证IP地址#

验证IP地址

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

#分类讨论就行
class Solution:
    def solve(self , IP: str) -> str:
        def is_hex(s):
            try:
                int(s, 16)
                return True
            except ValueError:
                return False
        def check_ip4(s):
            if s.isdigit():
                if -1<int(s)<256:
                    if len(s)==1:
                        return True
                    elif len(s)>1 and s[0] != '0':
                        return True
            return False
        def check_ip6(s):
            if is_hex(s):
                if len(s) > 1 and s == ''.zfill(len(s)):
                    return False
                return True
            return False
        if '.' in IP:
            ip = IP.split('.')
            for i in ip:
                if not check_ip4(i):
                    return 'Neither'
            return 'IPv4'
        else:
            ip = IP.split(':')
            for i in ip:
                if not check_ip6(i):
                    return 'Neither'
            return 'IPv6'
        
        
            

全部评论

相关推荐

2024-12-25 09:09
四川师范大学 运营
想和你交朋友的潜伏者要冲国企:先去沃尔玛亲身感受标准化流程体系,一两年后再跳槽国内任何零售行业,可以有更大选择权吧?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务