math syntax checker written in python

前端 未结 3 1764
情歌与酒
情歌与酒 2021-02-15 06:53

All I need is to check, using python, if a string is a valid math expression or not.

For simplicity let\'s say I just need + - * / operators (+ -

3条回答
  •  灰色年华
    2021-02-15 07:01

    You could try building a simple parser yourself to tokenize the string of the arithmetic expression and then build an expression tree, if the tree is valid (the leaves are all operands and the internal nodes are all operators) then you can say that the expression is valid.

    The basic concept is to make a few helper functions to create your parser.

    def extract() will get the next character from the expression
    def peek() similar to extract but used if there is no whitespace to check the next character
    get_expression()
    get_next_token()

    Alternatively if you can guarantee whitespace between characters you could use split() to do all the tokenizing.

    Then you build your tree and evaluate if its structured correctly

    Try this for more info: http://effbot.org/zone/simple-top-down-parsing.htm

提交回复
热议问题