0

I am fairly new to python/ programming in general and i am trying to write a function that will convert an equation passed in as a string to its numeric representation and do some basic calculations. I am having some trouble with the parenthesis as i am not sure how to represent them for order of operations.

Any help of tips would be greatly appreciated. Thank you!

EquationAsString ="( 2 + 3 ) * 5"

def toEquation(EquationAsString):
     Equation = EquationAsString.split(' ')
     #store info in list and use it like a stack, check the type etc.
     answer = 25
     return answer
6
  • Are spaces guaranteed to be the delimiter for input into your script?
    – lolsky
    Jun 12, 2019 at 23:13
  • This kind of exercise is typically one of the very first things that's taught when covering parsers in a formal computer science compiler-design class. There's no shortage of online examples; look for the ones where you're building and evaluating an abstract syntax tree to be going down the right path. Jun 12, 2019 at 23:16
  • 1
    I suspect that the question isn't the correct one you should be asking. This smells like a programming exercise and it doesn't appear you have thought through how you plan to "do some basic calculations" because, in the context of math equations, the parenthesis has no numerical equivalent. Jun 12, 2019 at 23:17
  • (To be clear -- many, if not most, of the answers to the linked duplicate questions do correctly handle parentheses). Jun 12, 2019 at 23:21
  • 1
    I would use Python Lex-Yacc to build parser. Or I would convert to Polish notation - "* + 2 3 5" - which doesn't need parentheses.
    – furas
    Jun 12, 2019 at 23:22

1 Answer 1

0

You can use the eval method to do such a thing.

Example:

print(eval('(2+3)*5'))

Output:

25

And if you really wanted to put it in a function:

def evaluation_string(input):
    print(eval(input))

Example

def evaluation_string(input):
    print(eval(input))

string_equation = '(2+3)*5'
evaluation_string(string_equation)

Output:

25
2
  • If eval is an adequate answer, the question is already in our knowledgebase. Note the "Answer Well-Asked Questions" section of How to Answer, and the bullet point therein regarding questions which "have been asked and answered many times before". Jun 12, 2019 at 23:18
  • 1
    Thank you , Eval is a great start and also the links provided by @CharlesDuffy help greatly! Thank you! Jun 13, 2019 at 1:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.