题解 | #验证IP地址#

验证IP地址

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

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 验证IP地址
# @param IP string字符串 一个IP地址字符串
# @return string字符串
#
import re
class Solution:
    def solve(self , IP: str) -> str:
        # write code here
        if self.is_v4(IP):
            return 'IPv4'
        if self.is_v6(IP):
            return 'IPv6'
        return 'Neither'
    
    @staticmethod
    def is_v4(ip):
        cells = ip.split('.')
        if cells.__len__() != 4: return False
        for cell in cells:
            try: 
                if 0>int(cell) or int(cell) > 255:
                    return False
            except: return False
            if re.findall(r'^\s*0[\d]?', cell): return False
        return True
    
    @staticmethod
    def is_v6(ip):
        cells = ip.split(':')
        if cells.__len__() != 8: return False
        for cell in cells:
            if not re.findall(r'^[0-9a-fA-F]{1,4}$', cell):
                return False
        return True
全部评论

相关推荐

狸猫换offer:神通广大的互联网
点赞 评论 收藏
分享
joecii:如果没有工资,那可能没有工资是这家公司最小的问题了
找实习记录
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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