题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
思路:
这道题有点取巧了,直接利用float强转,可得到答案。
当然也有其他方法,如也可以引入正则表达式进行匹配。
My Answer:
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
try:
return float(s)
except:
return 0
补充一种通用的解题思路:
首先,检测科学计数法中的标准 ‘e’,然后切分后前后两部分判定是否符合要求,具体可见代码。
Python version:
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
if not s:
return False
aList = [w.lower() for w in s]
if 'e' in aList:
index = aList.index('e')
front = aList[:index]
behind = aList[index+1:]
if '.' in behind or len(behind) == 0:
return False
isFrond = self.scanDigit(front)
isBehind = self.scanDigit(behind)
return isFrond and isBehind
else:
isNum = self.scanDigit(aList)
return isNum
def scanDigittwo(self, alist):
dotNum = 0
allowVal = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '.', 'e']
for index,count in alist:
if count not in allowVal:
return False
if count == '.':
dotNum += 1
if count in '+-' and index != 0:
return False
if dotNum > 1:
return False
return True
def scanDigit(self, alist):
dotNum = 0
allowVal = [str(i) for i in range(10)] + ['+', '-', '.', 'e']
for i in range(len(alist)):
if alist[i] not in allowVal:
return False
if alist[i] == '.':
dotNum += 1
if alist[i] in '+-' and i != 0:
return False
if dotNum > 1:
return False
return True