-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path7_bool.py
53 lines (46 loc) · 1.38 KB
/
7_bool.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
52
53
from pyparsing import Suppress, Keyword, Word, Forward, Group, ZeroOrMore, restOfLine
# <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>)
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)
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)