-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
98 lines (69 loc) · 1.97 KB
/
parser.py
File metadata and controls
98 lines (69 loc) · 1.97 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# Written by Alaa Ben Fatma 2019
import sys
# EXPRESSION
exp = []
index = 0
# Get the current value of the expression
def currentToken():
return exp[0]
# Jump to the next element of the expression
def next():
if(len(exp) > 1):
exp.remove(exp[0])
# Definitions
PLUS = '+'
MINUS = '-'
MULT = '*'
DIV = '/'
OB = '('
CB = ')'
# Return a number if the value of the token is numeric, check for brackets otherwise.
def factor(res):
if(str.isnumeric(currentToken())):
res = (float)(currentToken())
next()
return res
elif(currentToken() == OB):
next()
res = parse(res)
next()
return res
else:
return res
pass
# Perform multiplication & division for them being the operators with the highest priority
def high_priority_terms(res):
if(currentToken() == MULT):
next()
x = high_priority_terms(res)
y = factor(res)
res = x*y
elif(currentToken() == DIV):
next()
x = high_priority_terms(res)
y = factor(res)
res = x/y
return res
# Trigger the function above
def high_prio_terms_trigger(res):
res = factor(res)
return high_priority_terms(res)
# Perform addition & subtraction for them being the operators with the highest priority
def low_priority_terms(res):
if(currentToken() == PLUS):
next()
res = high_prio_terms_trigger(res) + low_priority_terms(res)
elif(currentToken() == MINUS):
next()
res = low_priority_terms(res) - high_prio_terms_trigger(res)
return res
# Trigger the function above
def low_priority_terms_trigger(res):
res = high_prio_terms_trigger(res)
return low_priority_terms(res)
# Parse the equation
def parse(res):
return low_priority_terms_trigger(res)
# Main ? (I know that you are laughing, C fans).
exp = sys.argv[1].split(' ')
print(parse(0.0))