【每日一题0802】IP地址验证

:woman_mage:编写一个python函数来识别有效的十进制点格式的 IPv4地址。如果 ip 包含四个八位字节,值在0到255之间,则应将其视为有效。

示例:

有效的IP地址

1.2.3.4
123.45.67.89

无效的IP地址

1.2.3
1.2.3.4.5
123.456.78.90
123.045.067.089

备注:前导0被视为无效,例如:01.02.03.04

题目难度:中等
题目来源:codewars

def is_valid_IP(ip: str) -> bool:
    pass
    
assert is_valid_IP('12.255.56.1') is True
assert is_valid_IP('abc.def.ghi.jkl') is False
assert is_valid_IP('123.456.789.0') is False
assert is_valid_IP('0.0.0.0') is True
assert is_valid_IP('01.02.03.04') is False
def is_valid_IP(ip: str) -> bool:
    ips = ip.split(".")
    if len(ips) == 4:
        for i in ips:
            if not i.isdigit() or (i.startswith("0") and len(i) > 1) or int(i) < 0 or int(i) > 255:
                return False
        return True
    else:
        return False


assert is_valid_IP('12.255.56.1') is True
assert is_valid_IP('abc.def.ghi.jkl') is False
assert is_valid_IP('123.456.789.0') is False
assert is_valid_IP('0.0.0.0') is True
assert is_valid_IP('01.02.03.04') is False

def is_valid_ip(ip:str)->bool:
    ip_list=ip.split('.')
    num=0
    for i in ip_list:
        if i.isdigit():
            if int(i)>=0 and int(i)<=255:
                if str(int(i))==i:
                    num=num+1
    if num==4:
        return True
    else:
        return False

image

def is_valid_IP(ip: str) -> bool:
    return True if (re.search(r'^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$', ip)) else False


assert is_valid_IP('12.255.56.1') is True
assert is_valid_IP('abc.def.ghi.jkl') is False
assert is_valid_IP('123.456.789.0') is False
assert is_valid_IP('0.0.0.0') is True

参考题解1:

from re import compile, match

def is_valid_IP(ip: str) -> bool:
    REGEX = compile(r'^((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}'
                r'(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$')
    return bool(match(REGEX, ip))

assert is_valid_IP('12.255.56.1') is True
assert is_valid_IP('abc.def.ghi.jkl') is False
assert is_valid_IP('123.456.789.0') is False
assert is_valid_IP('0.0.0.0') is True
assert is_valid_IP('01.02.03.04') is False

思路:利用正则表达式匹配来辅助判定字符串是否符合预期的格式。

参考题解2:

def is_valid_IP(ip: str) -> bool:
    return ip.count('.')==3 and all(o.isdigit() and 0<=int(o)<=255 and str(int(o))==o for o in ip.split('.'))

assert is_valid_IP('12.255.56.1') is True
assert is_valid_IP('abc.def.ghi.jkl') is False
assert is_valid_IP('123.456.789.0') is False
assert is_valid_IP('0.0.0.0') is True
assert is_valid_IP('01.02.03.04') is False

思路:利用python3内置函数all和元祖推导式,遍历检查逗号分隔的每个子串的格式是否符合IP地址的所有规则。all() 函数用于判断给定的可迭代参数iterable中的所有元素是否都为 True,如果是则返回 True,否则返回 False。元素除了是 0''NoneFalse 外都算 True

关闭