0

I want to make a user input an equation that I can work with in Python. How can I modify the raw_input formula that allows me to do this?

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?

Any help will be appreciated!

denis
  • 21,378
  • 10
  • 65
  • 88
  • 1
    Your equation resulted in 8 because in python `^` means `bitwise xor`. You should use `**` – Lafexlos Dec 14 '16 at 06:31
  • `parser` is Python's internal parser. You have to write *your own* parser to parse equations, or use one someone has already written. – juanpa.arrivillaga Dec 14 '16 at 06:36
  • checkout this question which will help you to create your own parser http://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string – Midhun Mohan Dec 14 '16 at 07:35

1 Answers1

0

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. 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:

# 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

Shiv
  • 1,912
  • 1
  • 15
  • 21