Python Solution Using Try/Except


  • 0
    L

    Re: Python Solution

    Similar to above solution but using try/except.

    
    class Solution(object):
        def validIPAddress(self, IP):
            """
            :type IP: str
            :rtype: str
            """
            V4 = "IPv4"
            V6 = "IPv6"
            NE  = "Neither"
            if not IP:
                return NE
            valid_chars="0123456789abcdefABCDEF"
            for i in range(0, len(IP)):
                if IP[i] == "." or IP[i] == ":" or IP[i] in valid_chars:
                    continue
                else:
                    return NE
            if "." in IP:
                iparr = IP.split(".")
                if len(iparr) != 4:
                    return NE
                try:
                    for oc in iparr:
                        if (len(oc)>1 and oc[0]=="0") or int(oc) <0 or int(oc)>0xFF:
                            return NE
                    return V4
                except ValueError:
                    return NE
            if ":" in IP:
                iparr = IP.split(":")
                if len(iparr) != 8:
                    return NE
                try:
                    for i, tbytes in enumerate(iparr):
                        if len(tbytes)>4 or int(tbytes,16) <0 or int(tbytes,16)>0xFFFF:
                            return NE
                except ValueError:
                    return NE
                return V6
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.