it is all about corner-cases...
class Solution(object): def validIP4(self, IP): def validNum4(s): try: # leading zero, negative if (s[0] == '0' and len(s) > 1) or s[0] == '-': return False # value range v = int(s) if not (v >= 0 and v <= 255): return False except ValueError: return False return True arr = IP.split(".") for s in arr: if len(s) == 0: return False if not validNum4(s): return False return True def validIP6(self, IP): def validNum6(s): s = s.lower() for c in s: if not ((c >= '0' and c <= '9') or (c >= 'a' and c <= 'f')): return False return True arr = IP.split(":") for s in arr: if len(s) == 0 or len(s) > 4: return False if not validNum6(s): return False return True def validIPAddress(self, IP): """ :type IP: str :rtype: str """ bIs4 = len(IP.split(".")) == 4 if bIs4: if self.validIP4(IP): return "IPv4" bIs6 = len(IP.split(":")) == 8 if bIs6: if self.validIP6(IP): return "IPv6" return "Neither"