简体   繁体   English

如何让用户输入可在python中使用的方程式?

[英]How do I get user to input an equation that I can use in python?

I want to make a user input an equation that I can work with in Python. 我想让用户输入可以在Python中使用的方程式。 How can I modify the raw_input formula that allows me to do this? 如何修改允许我执行此操作的raw_input公式?

Currently, I have this in my code: 目前,我的代码中包含以下内容:

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)

My constraints are the equations that I want the user to input. 我的约束是希望用户输入的方程式。 I want the equations to be in the format of <=. 我希望方程式的格式为<=。

I tried using parsers, so I tried a test case of using a parser and I ended up with this code. 我尝试使用解析器,因此尝试了使用解析器的测试案例,最终得到了这段代码。

import parser
formula = "x^2"
code = parser.expr(formula).compile()

from math import sin
x = 10
print(eval(code))

However, when I ran the code, Python gave me an answer of 8 when the answer is supposed to be 100. Is there a problem also with the parser code that I used? 但是,当我运行代码时,当答案应该为100时,Python给了我8的答案。我使用的解析器代码也存在问题吗?

Any help will be appreciated! 任何帮助将不胜感激!

You would need to parse the input string and build your formula. 您将需要解析输入字符串并构建您的公式。 For example say we want to raise 2 to the power 4 then you can take inputs like 2**4 or 2^4. 例如,假设我们想将2提高到4,那么您可以输入2 ** 4或2 ^ 4之类的输入。 In both the cases according to your symbols for equations you need to parse the string input and evaluate the equation. 在两种情况下,根据方程式的符号,您都需要解析字符串输入并评估方程式。

If you can provide test cases then I can probably help with parsing of string. 如果您可以提供测试用例,那么我可能可以帮助解析字符串。

Edit: Python uses ** for exponentiation but if you want user to use ^ as input then you can try following: 编辑:Python使用**进行幂运算,但是如果您希望用户使用^作为输入,则可以尝试以下操作:

# say s is input
[base, exponent] = s.split('^')
print (float(base)**float(exponent))

That should work. 那应该工作。 That way you have to build all formulas which you want to enter. 这样,您必须构建要输入的所有公式。 Complex formulas will require a more capable parser. 复杂的公式将需要更强大的解析器。 This is just something to begin with 这只是开始

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM