468. Validate IP Address - LeetCode Solution


String

Python Code:

class Solution:
    def validIPAddress(self, IP: str) -> str:
        def ipv4(ip):
            s=ip.split('.')
            if len(s)!=4:
                return False
            for e in s:
                try:
                    v=int(e)
                    if v>255 or e[0]=='-' or str(v)!=e:
                        return False
                except:
                    return False
            return True
        
        def ipv6(ip):
            s=ip.split(':')
            if len(s)!=8:
                return False
            
            for e in s:
                l=len(e)
                if l>4 or l==0:
                        return False
                try:
                    v=int(e,16)
                    if e[0] == '-':
                        return False
                    
                except:
                    return False
            return True
        
        ip=IP
               
        if '.' in ip and ipv4(ip):
            return 'IPv4'
        if ':' in ip and ipv6(ip):
            return 'IPv6'
            
        return 'Neither'


Comments

Submit
0 Comments
More Questions

514B - Han Solo and Lazer Gun
898B - Proper Nutrition
9C - Hexadecimal's Numbers
1265B - Beautiful Numbers
745A - Hongcow Learns the Cyclic Shift
873A - Chores
1754B - Kevin and Permutation
1547D - Co-growing Sequence
1754D - Factorial Divisibility
1117B - Emotes
412B - Network Configuration
845B - Luba And The Ticket
1732A - Bestie
389A - Fox and Number Game
1732B - Ugu
1100B - Build a Contest
1181B - Split a Number
1313B - Different Rules
1736D - Equal Binary Subsequences
1754A - Technical Support
26B - Regular Bracket Sequence
699A - Launch of Collider
474D - Flowers
1016A - Death Note
1335C - Two Teams Composing
1167C - News Distribution
813C - The Tag Game
1130C - Connect
1236B - Alice and the List of Presents
845C - Two TVs