HTMLify

LeetCode - Validate IP Address - Python
Views: 9 | Author: abh
class Solution:
    def validIPAddress(self, queryIP: str) -> str:
        if "." in queryIP:
            try:
                if queryIP[0]=="0"or(".0"in queryIP and ".0." not in queryIP):
                    raise ValueError
                ns = list(map(int, queryIP.split(".")))
                if len(ns) != 4:
                    raise ValueError
                for n in ns:
                    if not 0 <= n <= 255:
                        raise ValueError
                return "IPv4"
            except:
                pass
        if ":" in queryIP:
            try:
                for s in queryIP.split(":"):
                    if not 1 <= len(s) <= 4:
                        raise ValueError
                ns = list(map(lambda n: int(n, 16), queryIP.split(":")))
                if len(ns) != 8:
                    raise ValueError
                for n in ns:
                    if not 0 <= n <= 65535:
                        raise ValueError
                return "IPv6"
            except:
                pass
        return "Neither"

Comments