题目:请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
思路:判断s中所有字符串,以e为界,e后面不能出现.或空,否则直接返回False,然后把e前后两部分全部放到
一个判断函数里面,考虑所有出现的字符串,+-如果出现,必须出现在首位,字符串里面.出现次数不能超过1,而且不能出现在首尾。
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
if len(s) < 0:
return False
s = s.lower()
if 'e' in s:
if s.count('e') != 1:
return False
index_ = s.index('e')
front = s[:index_]
behind = s[index_+1:]
if len(behind) == 0 or '.' in behind:
return False
return self.isdigit(front) and self.isdigit(behind)
else:
return self.isdigit(s)
def isdigit(self, s):
necessary = ['0','1','2','3','4','5','6','7','8','9','+','-','.']
if s.count('.') > 1:
return False
for each in s:
if each not in necessary:
return False
if each in '+-' and s.index(each) != 0:
return False
if each in '.' and s.index(each) == 0:
return False
return True