0

I have a equation I get in a file something like (((2+1)*(4+5))/2). What I am looking for is the distinct mathematical expressions inside it. In this case: 2+1 4+5 (2+1)*(4+5) and finally ((2+1)*(4+5))/2.

I started by lookins at these How can I split a string of a mathematical expressions in python? But not able to arrive at a solution..

Can you please help.

d_luffy_de
  • 967
  • 1
  • 9
  • 24

1 Answers1

2

You can make a bare-bones parser by iterating through the string and each time you find an opening parenthesis, push the index to a stack. When you find a closing parenthesis, pop off the last thing the in the stack and take a slice from that to where you are now:

stack = []
s = "(((2+1)*(4+5))/2)"
for i, c in enumerate(s):
    if c == "(":
        stack.append(i+1)
    if c == ")":
        f = stack.pop()
        print(s[f:i])

Result

2+1
4+5
(2+1)*(4+5)
((2+1)*(4+5))/2

If pop() doesn't work or you have something left in the stack when you're done, you don't have balanced parenthesis — this can be fleshed out to do error checking.

Mark
  • 90,562
  • 7
  • 108
  • 148