码迷,mamicode.com
首页 > 编程语言 > 详细

Valid Number @python

时间:2015-04-07 22:58:36      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

 

直接上代码,特别是解法二,引入 re 模块匹配,很精简强大!

 

技术分享
 1 class InputType:
 2     INVALID = 0
 3     SPACE = 1
 4     SIGN =2
 5     DIGIT =3
 6     DOT = 4
 7     EXPONENT =5
 8     
 9 class Solution:
10     # @param s, a string
11     # @return a boolean
12     def isNumber(self, s):
13         transition_table = [[-1,  0,  3,  1,  2, -1],     # next states for state 0
14                             [-1,  8, -1,  1,  4,  5],     # next states for state 1
15                             [-1, -1, -1,  4, -1, -1],     # next states for state 2
16                             [-1, -1, -1,  1,  2, -1],     # next states for state 3
17                             [-1,  8, -1,  4, -1,  5],     # next states for state 4
18                             [-1, -1,  6,  7, -1, -1],     # next states for state 5
19                             [-1, -1, -1,  7, -1, -1],     # next states for state 6
20                             [-1,  8, -1,  7, -1, -1],     # next states for state 7
21                             [-1,  8, -1, -1, -1, -1]]     # next states for state 8
22                             
23         state = 0
24         for char in s:
25             inputType = InputType.INVALID
26             if char.isspace():
27                 inputType = InputType.SPACE;
28             elif char == + or char == -:
29                 inputType = InputType.SIGN
30             elif char in 0123456789:
31                 inputType =InputType.DIGIT
32             elif char  == .:
33                     inputType = InputType.DOT
34             elif char == e or char ==E:
35                 inputType = InputType.EXPONENT
36                 
37             state = transition_table[state][inputType]
38             if state == -1:
39                 return False
40         return state==1 or state==4 or state ==7 or state==8
41     
42     def isNumber2(self,s):
43         import re
44         return bool(re.match("^\s*[\+\-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$",s))
View Code

 

Valid Number @python

标签:

原文地址:http://www.cnblogs.com/jkmiao/p/4399677.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!