题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
class Solution: def solve(self, IP: str) -> str: def is_ipv4(ip): parts = ip.split(".") if len(parts) != 4: return False for part in parts: if ( not part.isdigit() or not 0 <= int(part) <= 255 or (len(part) > 1 and part[0] == "0") ): return False return True def is_ipv6(ip): parts = ip.split(":") if len(parts) != 8: return False for part in parts: if not ( 1 <= len(part) <= 4 and all([c in "0123456789abcdefABCDEF" for c in part]) ): return False return True if is_ipv4(IP): return "IPv4" elif is_ipv6(IP): return "IPv6" else: return "Neither"