题目:请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+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
''' 将E转换成e '''
s = s.lower()
if 'e' in s:
index_ = s.index('e')
front = s[:index_]
behind = s[index_+1:]
''' e后面的数字 不能是小数 可以有+-号'''
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','.']
begin = 0
if s.count('.') > 1:
return False
if s[0] in '+-':
begin = 1
for each in s[begin:]:
if each not in necessary:
return False
if s[0] == '.':
return False
return True