我想讓用戶輸入一個我可以在Python中使用的公式。我如何修改允許我這樣做的raw_input公式?如何讓用戶輸入我可以在python中使用的公式?
目前,我有這個在我的代碼:
consts = list()
nconst = int(input("How many constraints would you like to add? "))
for i in range(nconst):
const = input("Constraint " + str(i+1) + ": ")
consts.append(const)
我的約束,我想用戶輸入的公式。我希望公式的格式爲< =。
我嘗試過使用解析器,所以我嘗試了一個使用解析器的測試案例,並最終得到了這段代碼。
import parser
formula = "x^2"
code = parser.expr(formula).compile()
from math import sin
x = 10
print(eval(code))
然而,當我跑的代碼,Python的給我的8回答時的答案應該是100是否有問題還與我所使用的解析器代碼?
任何幫助將不勝感激!
您的等式導致8,因爲在Python中'^'意味着'bitwise xor'。你應該使用'**' – Lafexlos
'parser'是Python的內部解析器。你必須編寫*自己的*解析器來解析方程,或者使用已經寫好的人。 –
結帳這個問題,這將有助於你創建自己的解析器http://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string –