The problem is to write a function that determines whether a given string is a valid IPv4 or IPv6 address or neither.
An IPv4 address is formatted as four decimal numbers, each ranging from 0 to 255, separated by dots ("."
). Each part contains one to three digits. Leading zeros are not allowed (e.g., “192.168.01.1” is invalid, but “192.168.1.1” is valid).
An IPv6 address is formatted as eight groups of four hexadecimal digits, each group separated by a colon (":"
). Each hexadecimal digit is a digit or a letter from ‘a’ to ‘f’ or ‘A’ to ‘F’. Leading zeros are allowed in each group, but a group shouldn’t be empty (e.g., “2001:0db8:85a3:0000:0000:8a2e:0370:7334” is valid, but “2001:0db8:85a3::8a2e:0370:7334” is invalid).
The output should be:
def validIPAddress(IP: str) -> str:
def is_valid_ipv4(ip):
parts = ip.split(".")
if len(parts) != 4:
return False
for part in parts:
if not part.isdigit():
return False
if len(part) > 1 and part[0] == '0':
return False
if not 0 <= int(part) <= 255:
return False
return True
def is_valid_ipv6(ip):
parts = ip.split(":")
if len(parts) != 8:
return False
hexdigits = '0123456789abcdefABCDEF'
for part in parts:
if len(part) == 0 or len(part) > 4:
return False
for char in part:
if char not in hexdigits:
return False
return True
if IP.count('.') == 3 and is_valid_ipv4(IP):
return "IPv4"
elif IP.count(':') == 7 and is_valid_ipv6(IP):
return "IPv6"
else:
return "Neither"
"."
).":"
).Both validation methods are constant time operations since the given constraints ensure a fixed number of checks regardless of input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?