-
Notifications
You must be signed in to change notification settings - Fork 4
/
expressiongate.py
251 lines (203 loc) · 7.96 KB
/
expressiongate.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# from enum import Enum
# class Operator(Enum):
# AND = 'and'
# OR = 'or'
# EQUAL = '=='
# NOT_EQUAL = '!='
# LESS_THAN = '<'
# GREATER_THAN = '>'
# LESS_THAN_OR_EQUAL = '<='
# GREATER_THAN_OR_EQUAL = '>='
# from abc import ABC, abstractmethod
# class ExpressionComponent(ABC):
# @abstractmethod
# def evaluate(self, variables):
# pass
# class Expression(ExpressionComponent):
# def __init__(self, left_part, right_part, operation):
# self.left_expression = left_part
# self.right_expression = right_part
# self.operation = operation
# def evaluate(self, variables):
# value = None
# if self.operation == Operator.AND:
# value = self.left_expression.evaluate() and self.right_expression.evaluate()
# elif self.operation == Operator.OR:
# value = self.left_expression.evaluate() or self.right_expression.evaluate()
# elif self.operation == Operator.EQUAL:
# value = self.left_expression.evaluate() == self.right_expression.evaluate()
# elif self.operation == Operator.NOT_EQUAL:
# value = self.left_expression.evaluate() != self.right_expression.evaluate()
# elif self.operation == Operator.LESS_THAN:
# value = self.left_expression.evaluate() < self.right_expression.evaluate()
# elif self.operation == Operator.GREATER_THAN:
# value = self.left_expression.evaluate() > self.right_expression.evaluate()
# elif self.operation == Operator.LESS_THAN_OR_EQUAL:
# value = self.left_expression.evaluate() <= self.right_expression.evaluate()
# elif self.operation == Operator.GREATER_THAN_OR_EQUAL:
# value = self.left_expression.evaluate() >= self.right_expression.evaluate()
# print("Expression value is:", value)
# return value
# class Variable(ExpressionComponent):
# def __init__(self, name):
# self.name = name
# def evaluate(self, variables):
# return variables[self.name]
# class Literal(ExpressionComponent):
# def __init__(self, value):
# self.value = value
# def evaluate(self, variables):
# return self.value
# # if __name__ == '__main__':
# # variables = {
# # "age": 36,
# # "location": "Boston",
# # "name": "Bob"
# # }
# # name_var = Variable("name", variables)
# # location_var = Variable("location", variables)
# # age_var = Variable("age", variables)
# # # Logical Expression: name == "Bob" && age <= 45 && location != "NY"
# # equals_expr = Expression(name_var, Variable("Bob", {}), Operator.EQUAL)
# # age_expr = Expression(age_var, Variable(45, {}), Operator.LESS_THAN_OR_EQUAL)
# # location_expr = Expression(location_var, Variable("NY", {}), Operator.NOT_EQUAL)
# # and_expr1 = Expression(equals_expr, age_expr, Operator.AND)
# # final_expr = Expression(and_expr1, location_expr, Operator.AND)
# # print('Final result:', final_expr.evaluate()) # Output: True
# class ExpressionBuilder:
# def build(self, expression):
# tokens = expression.split()
# stack = []
# i = 0
# while i < len(tokens):
# token = tokens[i]
# print(token)
# if token in Operator:
# right = stack.pop()
# left = stack.pop()
# operator = token
# print(left, right, operator)
# stack.append(Expression(left, right, operator))
# else:
# if token.isdigit():
# stack.append(Literal(int(token)))
# elif token.startswith('"') and token.endswith('"'):
# stack.append(Literal(token.strip('"')))
# else:
# stack.append(Variable(token))
# i += 1
# # The final expression is the root of our composite tree
# return stack.pop()
# # Example usage
# variables = {
# "name": "Bob",
# "age": 36,
# "location": "Boston"
# }
# expression = 'name == "Bob" && age <= 45 && location != "NY"'
# expression_builder = ExpressionBuilder()
# root_expression = expression_builder.build(expression)
# result = root_expression.evaluate(variables)
# print(f"Output: {result}") # Output: True
import re
from abc import ABC, abstractmethod
# ExpressionComponent: The base class for all expression components
class ExpressionComponent(ABC):
@abstractmethod
def evaluate(self, variables):
pass
# Leaf classes for variables and literals
class Variable(ExpressionComponent):
def __init__(self, name):
self.name = name
def evaluate(self, variables):
return variables[self.name]
class Literal(ExpressionComponent):
def __init__(self, value):
self.value = value
def evaluate(self, variables):
return self.value
# Composite class for binary expressions
class BinaryExpression(ExpressionComponent):
def __init__(self, left, operator, right):
self.left = left
self.operator = operator
self.right = right
def evaluate(self, variables):
left_value = self.left.evaluate(variables)
right_value = self.right.evaluate(variables)
return self.operator.evaluate(left_value, right_value)
# Operator interface and concrete operators
class Operator(ABC):
@abstractmethod
def evaluate(self, left, right):
pass
class EqualsOperator(Operator):
def evaluate(self, left, right):
return left == right
class NotEqualsOperator(Operator):
def evaluate(self, left, right):
return left != right
class LessThanOrEqualsOperator(Operator):
def evaluate(self, left, right):
return left <= right
class GreaterThanOrEqualsOperator(Operator):
def evaluate(self, left, right):
return left >= right
class AndOperator(Operator):
def evaluate(self, left, right):
return left and right
class OrOperator(Operator):
def evaluate(self, left, right):
return left or right
# Factory to create operator instances
class OperatorFactory:
def __init__(self):
self.operators = {
"==": EqualsOperator(),
"!=": NotEqualsOperator(),
"<=": LessThanOrEqualsOperator(),
">=": GreaterThanOrEqualsOperator(),
"&&": AndOperator(),
"||": OrOperator()
}
def get_operator(self, symbol):
return self.operators.get(symbol)
# Expression builder with improved tokenization
class ExpressionBuilder:
def __init__(self, operator_factory):
self.operator_factory = operator_factory
def tokenize(self, expression):
# Tokenizes based on operators, strings, variables, and numbers
token_pattern = re.compile(r'(\w+|"[^"]*"|\d+|&&|\|\||==|!=|<=|>=|<|>|[()])')
return token_pattern.findall(expression)
def build(self, expression):
tokens = self.tokenize(expression)
stack = []
for token in tokens:
if token in self.operator_factory.operators:
right = stack.pop()
left = stack.pop()
operator = self.operator_factory.get_operator(token)
stack.append(BinaryExpression(left, operator, right))
else:
if token.isdigit():
stack.append(Literal(int(token)))
elif token.startswith('"') and token.endswith('"'):
stack.append(Literal(token.strip('"')))
else:
stack.append(Variable(token))
# The final expression is the root of our composite tree
return stack.pop()
# Example usage
variables = {
"name": "Bob",
"age": 36,
"location": "Boston"
}
expression = 'name == "Bob" && age <= 45 && location != "NY"'
operator_factory = OperatorFactory()
expression_builder = ExpressionBuilder(operator_factory)
root_expression = expression_builder.build(expression)
result = root_expression.evaluate(variables)
print(f"Output: {result}") # Output: True