axiacore / py-expression-eval

MIT License
149 stars 54 forks source link

Negative multiplication since 0.3.10 broken #61

Open cloudition opened 3 years ago

cloudition commented 3 years ago

In version 0.3.9 it is possible to calculate: 2*-2 In versoin 0.3.10 this is no more possible. You will get a error "pop from empty list".

Martysh12 commented 3 years ago

The same thing is happening with division. When you try to divide, for example, 10 / -5, you get a "pop from empty list" error.

AlbCM commented 3 years ago

Same issue here image

dmpayton commented 1 year ago

I'm currently getting bit by this as well. It seems you can multiply negative numbers if the negative comes first.

>>> parser.parse('2 * -1').toString()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/vagrant/.virtualenvs/venv/lib/python3.8/site-packages/py_expression_eval/__init__.py", line 163, in toString
    n1 = nstack.pop()
IndexError: pop from empty list

>>> parser.parse('-1 * 2').toString()
'((-1)*2)'

For the moment, the workaround seems to be to wrap negative numbers in parens:

>>> parser.parse('2 * (-1)').toString()
'(2*(-1))'
kcrossen commented 2 months ago

Leading minus sign in context where subtraction makes no sense (would be a grammar error) should have the highest priority. Otherwise, there will be a (R-associative) negation operator left at the end of the dance with no dance partner. change py_expression_eval/init.py line 455 from: self.tokenprio = 5 to: self.tokenprio = 10 currently:: while self.pos < len(self.expression): if self.isOperator(): if self.isSign() and expected & self.SIGN: if self.isNegativeSign(): self.tokenprio = 5 self.tokenindex = '-' noperators += 1 self.addfunc(tokenstack, operstack, TOP1) change to: while self.pos < len(self.expression): if self.isOperator(): if self.isSign() and expected & self.SIGN: if self.isNegativeSign(): self.tokenprio = 10 self.tokenindex = '-' noperators += 1 self.addfunc(tokenstack, operstack, TOP1)