問(wèn)題描述
設(shè)計(jì)一個(gè)算法窒篱,判斷點(diǎn)分十進(jìn)制格式的IPv4地址是否符合協(xié)議要求淹魄。函數(shù)的輸入限制為一個(gè)字符串告匠。
合理的輸入:1.2.3.4 123.45.67.89
不合理的輸入:1.2.3 1.2.3.4.5 123.456.78.90 123.045.067.089
問(wèn)題標(biāo)簽
算法蛛倦、正則表達(dá)式耻煤、高級(jí)語(yǔ)言特性晾匠、基礎(chǔ)知識(shí)茶袒、字符串、聲明式編程(Declarative Programming)
函數(shù)命名
def is_valid_IP(strng):
return None
測(cè)試用例
Test.assert_equals(is_valid_IP('12.255.56.1'), True)
Test.assert_equals(is_valid_IP(''), False)
Test.assert_equals(is_valid_IP('abc.def.ghi.jkl'), False)
Test.assert_equals(is_valid_IP('123.456.789.0'), False)
Test.assert_equals(is_valid_IP('12.34.56'), False)
Test.assert_equals(is_valid_IP('12.34.56 .1'), False)
Test.assert_equals(is_valid_IP('12.34.56.-1'), False)
Test.assert_equals(is_valid_IP('123.045.067.089'), False)
原文鏈接
http://www.codewars.com/kata/ip-validation/python
編程派解法
def is_valid_IP(s):
a = s.split('.')
if len(a) != 4:
return False
for x in a:
if not x.isdigit() or x.startswith('0'):
return False
i = int(x)
if i < 0 or i > 255:
return False
return True
網(wǎng)友解法摘錄
網(wǎng)友cwhy:獲得最佳實(shí)踐推薦12次
def is_valid_IP(strng):
lst = strng.split('.')
passed = 0
for sect in lst:
if sect.isdigit():
if sect[0] != '0':
if 0 < int(sect) <= 255:
passed += 1
return passed == 4
網(wǎng)友saurus:使用正則表達(dá)式
import re
def is_valid_IP(strng):
return re.match('\.'.join(['(\d|1?\d\d|2[0-4]\d|25[0-5])']*4) + '$', strng) is not None
網(wǎng)友pacofvf:超長(zhǎng)一行流
import re
def is_valid_IP(address):
return bool(re.match("^([1][0-9][0-9]\.|^[2][5][0-5].|^[2][0-4][0-9]\.|^[1][0-9][0-9]\.|^[0-9][0-9]\.|^[0-9]\.)([1][0-9][0-9]\.|[2][5][0-5]\.|[2][0-4][0-9]\.|[1][0-9][0-9]\.|[0-9][0-9]\.|[0-9]\.)([1][0-9][0-9]\.|[2][5][0-5]\.|[2][0-4][0-9]\.|[1][0-9][0-9]\.|[0-9][0-9]\.|[0-9]\.)([1][0-9][0-9]|[2][5][0-5]|[2][0-4][0-9]|[1][0-9][0-9]|[0-9][0-9]|[0-9])$",address))
網(wǎng)友natict:更簡(jiǎn)單的一行流
def is_valid_IP(s):
return s.count('.')==3 and all(o.isdigit() and 0<=int(o)<=255 and str(int(o))==o for o in s.split('.'))