-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8_bool_infix.py
51 lines (43 loc) · 1.2 KB
/
8_bool_infix.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from pyparsing import Keyword, Word, infixNotation, opAssoc
# <constant> ::= False | True
# <variable> ::= 'p' | 'q' | 'r'
# <or> ::= 'or'
# <and> ::= 'and'
# <not> ::= 'not'
# <expression> ::= <term> { <or><term> }
# <term> ::= <factor> { <and><factor> }
# <factor> ::= <constant> | <not><factor> | (<expression>)
constant = Keyword('True') | Keyword('False')
variable = Word('pqr', exact=1)
operand = constant | variable
expr = infixNotation(operand, [
("not", 1, opAssoc.RIGHT, ),
("and", 2, opAssoc.LEFT, ),
("or", 2, opAssoc.LEFT, ),
])
test_strings = [
'True',
'not True',
'p',
'q and r',
'(q and r)',
'(False)',
'(p and True)',
'(p and q) or p',
'(p and (not q or r)) or p',
]
for test in test_strings:
print(expr.parseString(test))
# l_par, r_par = Suppress('('), Suppress(')')
#
# and_op = Keyword('and')
# or_op = Keyword('or')
# not_op = Keyword('not')
# variable = Word('pqr', exact=1)
# constant = Keyword('True') | Keyword('False')
#
# expr = Forward()
# factor = Forward()
# factor <<= constant | variable | Group(not_op + factor) | Group(l_par + expr + r_par)
# term = factor + ZeroOrMore(and_op + factor)
# expr <<= term + ZeroOrMore(or_op + factor)