-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0005.py
More file actions
50 lines (36 loc) · 1.83 KB
/
0005.py
File metadata and controls
50 lines (36 loc) · 1.83 KB
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
import logging
import combinators.core as core
import combinators.operators as operators
import combinators.tokenization as tokenization
logging.basicConfig (level = logging.INFO)
logger = logging.getLogger (__name__)
specifications = [ ( "INTEGER", ( "[0-9]+", ) ),
( "SPACE", ( "[ \t]+", ) ),
( "PLUS", ( "\+", ) ),
( "MINUS", ( "-", ) ),
( "TIMES", ( "\*", ) ),
( "DIVIDE", ( "/", ) ),
( "POWER", ( "\^", ) ), ]
tokenizer = tokenization.filtered (tokenization.create (specifications), tokenization.strip ([ "SPACE" ]))
integer = core.token_type ("INTEGER")
primary = integer
operator_table = [ [ operators.OperatorInfix ("^", operators.Associativity.RIGHT),
operators.OperatorInfix ("$", operators.Associativity.RIGHT), ],
[ operators.OperatorInfix ("*", operators.Associativity.LEFT),
operators.OperatorInfix ("/", operators.Associativity.LEFT), ],
[ operators.OperatorInfix ("+", operators.Associativity.LEFT),
operators.OperatorInfix ("-", operators.Associativity.LEFT), ], ]
expression = operators.build (operator_table, primary)
try:
logger.info (expression.name)
logger.info (expression.parse (list (tokenizer ("1 + 2 + 3"))))
logger.info (expression.name)
logger.info (expression.parse (list (tokenizer ("1 ^ 2 ^ 3"))))
logger.info (expression.name)
logger.info (expression.parse (list (tokenizer ("1 + 2 * 3 + 4"))))
logger.info (expression.name)
logger.info (expression.parse (list (tokenizer ("2^3+4^5"))))
logger.info (expression.name)
logger.info (expression.parse (list (tokenizer ("1 + 2 - 3 + 4 - 5 + 6"))))
except core.Error as error:
logger.info (repr (error))