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(...)'得到你想要的。 –