0

The overall goal is to solve a simple linear [one var] equation in the same way that a human would. So, finding the most nested (), distributing until all the multiplication is done. (then combining like terms and then dividing one side of x's to the other side of constants)

I'm trying to find the order of operations in a Python equation. For instance, in something like

3(18(7x-3)+x) = 90

I would want to find the most nested set of () [in this case is 7x-3] and work out from there. I'm not sure if RegEx would be the best way to do this in Python. Furthermore, I'm using SymPy, so in several cases, when I find the most nested () there will not be anything to solve because the first step is only multiplication anyways.

Nate Cook3
  • 586
  • 1
  • 7
  • 19
  • you mean this `(?<=\()[^()]*(?=\))` – Avinash Raj May 03 '15 at 12:00
  • Don't use regexes, it's not the right tool. you need context-free grammars, one good reason for this is precedence handling. I wrote a [related](http://stackoverflow.com/a/29996191/3764814) answer recently, not in Python but it can show you how to approach this kind of problem. – Lucas Trzesniewski May 03 '15 at 12:03
  • @avinash-raj that expression isn't working for me, at least, not like this: part = re.match('(?<=\()[^()]*(?=\))', string) – Nate Cook3 May 03 '15 at 12:16
  • @LucasTrzesniewski that looks like a bit overkill for what I'm trying to do, but I'm still understanding it! SymPy can pretty much do all the computations I need, I'm just trying to make SymPy 'slow down' so to speak, and do smaller parts at a time so that the user can see whats going on. So, I want to break up SymPy's operations to the innermost () and work outwards, so that I can see a progression. One step at a time so to speak. Make sense? – Nate Cook3 May 03 '15 at 12:17
  • @NateCook3 [`\(([^()]+)\)`](https://regex101.com/r/yO3rH8/1) – Lucas Trzesniewski May 03 '15 at 12:20

1 Answers1

1

Use re.search instead of re.match because match tries to match from the beginning of the input string.

>>> import re
>>> s = '3(18(7x-3)+x) = 90'
>>> re.search(r'(?<=\()[^()]*(?=\))', s).group()
'7x-3'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • This works, but how do you work your way out of the middle? Sorry if that's not clear, but in the OP I wanted to find the most nested, solve it, and then find the next most nested () and perform a calculation on it, before working up again. – Nate Cook3 May 03 '15 at 14:15
  • @Nate you replace the match with the solved value, then you try to match again on this new string. – Lucas Trzesniewski May 03 '15 at 20:48