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
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Are spaces guaranteed to be the delimiter for input into your script? – lolsky Jun 12 '19 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. – Charles Duffy Jun 12 '19 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. – Brendon Whateley Jun 12 '19 at 23:17
  • (To be clear -- many, if not most, of the answers to the linked duplicate questions *do* correctly handle parentheses). – Charles Duffy Jun 12 '19 at 23:21
  • 1
    I would use [Python Lex-Yacc](http://www.dabeaz.com/ply/ply.html) to build parser. Or I would convert to [Polish notation](https://en.wikipedia.org/wiki/Polish_notation) - `"* + 2 3 5"` - which doesn't need parentheses. – furas Jun 12 '19 at 23:22
  • Found my answer, Thank you all! and @CharlesDuffy for the links! – andrep porte Jun 13 '19 at 01:30

1 Answers1

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
Edeki Okoh
  • 1,786
  • 15
  • 27
  • If `eval` is an adequate answer, the question is already in our knowledgebase. Note the "Answer Well-Asked Questions" section of [How to Answer](https://stackoverflow.com/help/how-to-answer), and the bullet point therein regarding questions which "have been asked and answered many times before". – Charles Duffy Jun 12 '19 at 23:18
  • 1
    Thank you , Eval is a great start and also the links provided by @CharlesDuffy help greatly! Thank you! – andrep porte Jun 13 '19 at 01:29