1
我是一名初学者,使用Python 2.79进行编程。我正在编写一个程序“标记”一个数学公式,基本上将每个数字和运算符转换为列表中的一个项目。输入命令将输入视为int而不是Python中的str
我的问题是目前(因为它是一个语义错误,我还没有能够测试其余的代码呢)在我的输入命令。我要求用户输入一个数学公式。 Python将其解释为一个int。
我试图使它成为一个字符串,和Python基本解决了配方,并运行的解决方案通过我的记号化功能
我的代码如下:
#Turn a math formula into tokens
def token(s):
#Strip out the white space
s.replace(' ', '')
token_list = []
i = 0
#Create tokens
while i < len(s):
#tokenize the operators
if s[i] in '*/\^':
token_list.append(s[i])
#Determine if operator of negation, and tokenize
elif s[i] in '+-':
if i > 0 and s[i - 1].isdigit() or s[i - 1] == ')':
token_list.append(s[i])
else:
num = s[i]
i += 1
while i < len(s) and s[i].isdigit():
num += s[i]
i += 1
token_list.append(num)
elif s[i].isdigit():
num = ''
while i < len(s) and s[i].isdigit():
num += s[i]
i += 1
token_list.append(num)
else:
return []
return token_list
def main():
s = str(input('Enter a math equation: '))
result = token(s)
print(result)
main()
任何帮助,将不胜感激
我期待到
使用'raw_input'代替输入。输入很烂。 –
在Python 2.x中,你必须使用'raw_input',而不是'input'。 – Barmar
另外,'str.replace()'不能就地工作。做's = s.replace(...)'得到你想要的。 –