How to make a parser that will make parentheses according arithmetical priority in expressions using the pyparsing
library?
for example *
has higher priority than +
.
It should do like this:
»> print(wholeexp.parseString('3+5-2'))
[[['3', '+', '5'], '-', '2']]
»> print(wholeexp.parseString('3+(5-2)'))
[['3', '+', ['5', '-', '2']]]
»> print(wholeexp.parseString('3+5-2*4'))
[[['3', '+', '5'], '-', ['2', '*', '4']]]
I tried the following, but it doesn't work very well. How should we change expr here:
from pyparsing import *
numb = Word(nums)
leftpar = Suppress('(')
rightpar = Suppress(')')
expr = Forward()
expr << Or( [numb,
Group(leftpar + expr + "+" + expr + rightpar),
Group(leftpar + expr + "-" + expr + rightpar),
Group(leftpar + expr + "*" + expr + rightpar)] )
wholeexp = expr + StringEnd()