题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 验证IP地址
# @param IP string字符串 一个IP地址字符串
# @return string字符串
#
class Solution:
def solve(self , IP: str) -> str:
# IPv6
if '.' in IP:
list1=IP.split('.')
# (1)用0开头不行
count1=0
for i in list1:
if i.startswith('0'):
return 'Neither'
else:
count1=count1+1
# (2)4个十进制数,范围均为0-255
count2=0
for i in list1:
if i<'0' or i>'255':
return 'Neither'
else:
count2=count2+1
if count2==len(list1) and count1==len(list1):
return "IPv4"
else:
return 'Neither'
# IPv6
elif ':' in IP:
list2=IP.split(':')
# (1)地址不等于八组
if len(list2)!=8:
return 'Neither'
for i in list2:
# (2)有空组
if i=='':
return 'Neither'
# (3)某个组的长度大于4
if len(i)>4:
return 'Neither'
# (4)包含不等于(a~f/A~F)的字母
for j in i:
if (j>='g' and j<='z') or (j>='G' and j<='Z'):
return 'Neither'
return "IPv6"