问题描述
我正在尝试构建一种将中缀转换为后缀的算法。下面是示例输入。你可以看到它都是一个没有空格的字符串。此外,输入可以将浮点数或整数作为操作数。我想弄清楚如何从左到右并确定一个元素是否是一个操作数(浮点数或整数)。
theInput1 = "3.2+.4*5.67/6.145="
theInput2 = "11.897/3.4+9.2-0.4*6.9/12.6-16.7="
theInput3 = "234+34*65="
theInput4 = "(12+3)*(56/2)/(34-4)="
这里有人帮助处理正则表达式:
import re
a = "11.897/3.4+9.2-0.4*6.9/12.6-16.7="
a2 = [x for x in re.split("(\d*\.?\d*)",a) if x != '']
print(a2)
s = []
for i in a2:
if i >= '0' and i <= '9':
s.append(i)
print(s)
这是正则表达式后的 a2:
['11.897','/','3.4','+','9.2','-','0.4','*','6.9','12.6','16.7','=']
看起来我得到了我需要的东西:
['11.897','16.7']
解决方法
您可能正在寻找这样的东西?
import re
theInput1 = "234+34*65="
theInput1 = re.split("(12+3)*(56/2)/(34-4)=",theInput1)
x = [char for char in theInput1 if char != '']
def typeOf(s):
try:return int(s)
except ValueError:return float(s)
for nums in x:
y = typeOf(nums)
print(type(y))