-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenizer.py
58 lines (44 loc) · 1.5 KB
/
tokenizer.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
54
55
56
57
58
"""Modul omogućava parsiranje aritmetičkih izraza."""
import re
__author__ = 'mijicd'
REGEX = r'(?:\d*\.\d+)|(?:\d+)|(?:[()+\-\^/*])'
class ExpressionNotStringError(Exception):
pass
class UnknownCharacterError(Exception):
pass
class InvalidMathematicalExpressionError(Exception):
pass
def tokenize(expression):
"""Funkcija kreira tokene na osnovu zadatog izraza.
Postupak formiranja liste tokena koristi regularni izraz
zadat putem REGEX varijable. Omogućeno je pronalaženje
sledećih tipova tokena:
- floating-point vrednosti
- celobrojne vrednosti
- operatori +, -, *, /, ^
- zagrade
Args:
expression (string): Izraz koji se parsira.
Returns:
list: Lista pronađenih tokena.
Raises:
AssertionError: Ako izraz nije zadat kao string.
"""
if not isinstance(expression, str):
raise ExpressionNotStringError("Izraz treba da bude string.")
tokens = re.findall(REGEX, expression)
if expression.replace(" ", "") != "".join(tokens):
raise UnknownCharacterError("Izraz sadrži karaktere koji nisu podržani.")
operations = ["+", "-", "*", "/", "^", "(", ")"]
unary_minus = True
multiple_exponent = True
output = []
for token in tokens:
if token not in operations:
unary_minus = False
if token == "(":
unary_minus = True
if token == "-" and unary_minus:
token = "~"
output.append(token)
return output