python实现无符号数识别
无符号数识别状态图为:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 16:06:51 2020
@author: 侯
"""
# * 状态有
# * -1: end_state
# * 0 :
# * 读取 数字 -> 1
# * 读取 'e' -> 3
# *
# * 1 :
# * 读取 数字 -> 1
# * 读取 '.' -> 2
# * 读取 'E'或'e' -> 4
# * 2 :
# * 读取 数字 -> 2
# * 读取 'E'或'e' -> 4
# * 3:
# * 读取 数字 -> 2
# * 4:
# * 读取 +/- -> 5
# * 读取 数字 -> 6
# * 5:
# * 读取 数字 -> 6
# * 6:
# * 读取 数字 -> 6
#验证s是否为无符号实数
def Test(s):
#digit代表数字
digit=['0','1','2','3','4','5','6','7','8','9']
result=''#识别结果
power=''#指数幂
start_state=0#开始状态为0
end_state=-1#结束状态设为-1
for i in range(len(s)):
if start_state==0:#开始状态为0
if s[i]=='.':#读取的字符是'.'时,进入状态3
start_state=3
result=result+'0'+s[i]
elif s[i] in digit:#读取的字符是数字时,进入状态1
start_state=1
result=result+s[i]
else:
start_state=-1
break
elif start_state==1:#开始状态为1
if s[i] in digit:#读取的字符是数字时,进入状态1
start_state=1
result=result+s[i]
elif s[i]=='.':#读取的字符是'.'时,进入状态2
start_state=2
result=result+s[i]
elif s[i]=='E' or s[i]=='e':#读取的字符是'E'或'e'时,进入状态4
start_state=4
else:
start_state=-1
break
elif start_state==2:#开始状态为2
if s[i] in digit:#读取的字符是数字时,进入状态2
start_state=2
result=result+s[i]
elif s[i]=='E' or s[i]=='e':#读取的字符是'E'或'e'时,进入状态4
start_state=4
else:
start_state=-1
break
elif start_state==3:#开始状态为3
if s[i] in digit:#读取的字符是数字时,进入状态2
start_state=2
result=result+s[i]
else:
start_state=-1
break
elif start_state==4:#开始状态为4
if s[i]=='+' or s[i]=='-':#读取的字符是'+'或'-'时,进入状态5
start_state=5
power=power+s[i]
elif s[i] in digit:#读取的字符是数字时,进入状态6
start_state=6
power=power+s[i]
else:
start_state=-1
break
elif start_state==5:#开始状态为5
if s[i] in digit:#读取的字符是数字时,进入状态6
start_state=6
power=power+s[i]
else:
start_state=-1
break
elif start_state==6:#开始状态为6
if s[i] in digit:#读取的字符是数字时,进入状态6
start_state=6
power=power+s[i]
else:
start_state=-1
break
if start_state==end_state or s=='.':
print(s+"不是无符号实数")
else:
if power!='':
result=str(float(result)*(10**int(power)))
print(s+" 是 "+result)
if __name__=='__main__':
test=['123','12.3','.123','123.','.','123e4',
'456E3','1.23e+4','8.9E+2','.123e-4',
'.34E-4','123.e4','123.e+4','123.e-4',
'623.E-4','31*54','bfg','12a','a3','1..3']
for i in range(len(test)):
Test(test[i])
运行结果如下图所示: