Skip to content

Instantly share code, notes, and snippets.

@ssshukla26
Created November 14, 2021 23:54
Show Gist options
  • Save ssshukla26/94568369acdf475f2623e5d0763fb8eb to your computer and use it in GitHub Desktop.
Save ssshukla26/94568369acdf475f2623e5d0763fb8eb to your computer and use it in GitHub Desktop.
Validate IP Address [LeetCode 468]
import re
class Solution:
def validIPAddress(self, queryIP: str) -> str:
def is_ipv4(ip: str) -> bool:
ip = ip.split(".")
if len(ip) == 4: # must have 4 different parts
# For each part
for part in ip:
if not (0 < len(part) <= 3): # length between 1 and 3
return False
elif part != "0" and re.match(r"0{1,}", part): # no trailing zeros
return False
elif re.search(r"[a-zA-Z]", part): # not alphabets present
return False
elif not (0 <= int(part) <= 255): # between 0 and 255
return False
else:
pass
return True
return False
def is_ipv6(ip: str) -> bool:
ip = ip.split(":")
if len(ip) == 8: # must have 8 different parts
# For each part
for part in ip:
if not (0 < len(part) <= 4): # length between 1 and 4
return False
elif re.search(r"[g-zG-Z]", part): # no alphabets except a to f or A to F
return False
else:
pass
return True
return False
# Main logic
if is_ipv4(queryIP):
return "IPv4"
elif is_ipv6(queryIP):
return "IPv6"
else:
return "Neither"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment