1

I am writing a boolean expression analyzer using PyParsing, I got the pyparsing.ParseResults class which looks like this:
[[[[['A1'], 'and', ['not', ['B2']], 'and', [[['C3'], 'or', [['D3'], ' and ', [' F2 ']]]]],' or ', [[' F2 '],' and ', [' G2 ']]]]]
The question is how to parse the resulting class instance before answering.
In my case A1, B2 are variables containing float
not - will return a negative value of the operand (not 0.5 = -0.5)
and - must select the minimum of the operands (0.2 and 0.3 and 0.4 = 0.2)
or - must select the maximum of the operands (0.2 or 0.3 or 0.4 = 0.4)

My code:

import pyparsing as pp

def parsing(parse_string):   
    complex_expr = pp.Forward()
    vars = pp.Word(pp.alphas, pp.alphanums)
    clause = pp.Group(vars ^ (pp.Suppress("(") + complex_expr + pp.Suppress(")") ))

    expr = pp.infixNotation(clause,[
                                ('not', 1, pp.opAssoc.RIGHT,),
                                ("and", 2, pp.opAssoc.LEFT, ),
                                ("or", 2, pp.opAssoc.LEFT, ),])
    complex_expr << expr
    parse_result=complex_expr.parseString(parse_string)
    return parse_result

parse_result = parsing('( A1 and not B2 and ( C3 or D3 and F2 ) or F2 and G2 )')
SegaSta
  • 31
  • 3
  • Please visit this related question and the extensive answer provided: https://stackoverflow.com/questions/64709299/pyparsing-evaluating-expression – PaulMcG Dec 12 '20 at 21:27
  • Thanks for this post, I didn’t find it on my own. However, I could not figure out the provided code, or rather adapt this solution for myself (( – SegaSta Dec 14 '20 at 14:29

0 Answers0