0

For the purpose of writing a calculator, like the python interpeter, I want to check the validity of my expressions.

I want to check a string for repeated mathematical operators, I don't want to catch anything, just to know if they exist, in which case the expression would be invalid.

4++-+4 is valid.

4*-8 is invalid

4-/7 is invalid

4/-4 is valid, mine probably fails here.

minut and plus can repeat themselves, but -* is, for example, invalid. Much like the way the python interpeter works. This is what I have, as a Regex, but any simpler solution is welcome, even not regex is great.

[*/^%\-+][*/^%] | [\-+*/^%][*/^%]

Link

Basicially, check if operators */^%-+ are either preceded by or followed by */^% (without minus and plus)

1 Answers1

1

Again a more concise solution would be either a CFG or a stack based approach for infix expressions. However something you could hack and experiment with is the following idea.

construct a product of all operators like so:

from itertools import product as p
all=list(p('*/^%-+',repeat=2))
all=map(lambda x:''.join(x),all)

invalids=[..write them by hand in here(hacky part)]
valids=filter(lambda x:x not in invalids,all)

And now you're left with all valid operations of length 2. You can scan your string with a window of 2, and when you find a pair of operators not belonging in the valids you can declare the expression invalid and move on.

Another way you could go about it is a rule-based one. Construct a dictionary with operators as keys, and for each operator the value would be a list holding all operators that can follow it.

Then your problem becomes one of checking your string at character i with the validity condition being

string[i+1] in dictionary[string[i]]

If you do find a CFG solution and its beautiful, let me know

themistoklik
  • 880
  • 1
  • 8
  • 19