-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01-interpreter-pattern.py
More file actions
831 lines (597 loc) · 25.7 KB
/
01-interpreter-pattern.py
File metadata and controls
831 lines (597 loc) · 25.7 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
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
"""Question: Implement the Interpreter pattern to define grammar and interpret language expressions.
Create a simple calculator that can interpret and evaluate mathematical expressions
with variables, using the Interpreter pattern to parse and execute expressions.
Requirements:
1. Create Expression interface with interpret() method
2. Implement terminal expressions (Number, Variable)
3. Implement non-terminal expressions (Add, Subtract, Multiply, Divide)
4. Create Context class to store variable values
5. Build expression trees for complex expressions
6. Demonstrate parsing and evaluation of expressions
Example usage:
context = Context()
context.set_variable("x", 10)
context.set_variable("y", 5)
expression = AddExpression(Variable("x"), Variable("y"))
result = expression.interpret(context) # Returns 15
"""
# LEARNING CHALLENGE
#
# Before looking at any solution below, please try to solve this yourself first!
# Try to implement your solution here:
# (Write your code below this line)
# ===============================================================================
# STEP-BY-STEP SOLUTION
# ===============================================================================
#
# CLASSROOM-STYLE WALKTHROUGH
#
# Let's solve this problem step by step, just like in a programming class!
# Each step builds upon the previous one, so you can follow along and understand
# the complete thought process.
#
# ===============================================================================
# Step 1: Import modules and create the Expression interface and Context class
# ===============================================================================
# Explanation:
# The Interpreter pattern starts with an abstract expression interface that defines
# the interpret method. We also need a Context class to store variable values.
from abc import ABC, abstractmethod
from typing import Dict, Any
class Context:
"""Context class to store variable values and state."""
def __init__(self):
self._variables: Dict[str, float] = {}
def set_variable(self, name: str, value: float):
"""Set a variable value in the context."""
self._variables[name] = value
def get_variable(self, name: str) -> float:
"""Get a variable value from the context."""
if name not in self._variables:
raise ValueError(f"Variable '{name}' is not defined")
return self._variables[name]
def has_variable(self, name: str) -> bool:
"""Check if a variable exists in the context."""
return name in self._variables
class Expression(ABC):
"""Abstract expression interface."""
@abstractmethod
def interpret(self, context: Context) -> float:
"""Interpret the expression and return the result."""
pass
# What we accomplished in this step:
# - Created the Context class to store variable values
# - Created the abstract Expression interface with interpret method
# Step 2: Create terminal expressions (Number and Variable)
# ===============================================================================
# Explanation:
# Terminal expressions are the leaf nodes in the expression tree. They don't
# contain other expressions. Number represents literal values, Variable represents named values.
from abc import ABC, abstractmethod
from typing import Dict, Any
class Context:
"""Context class to store variable values and state."""
def __init__(self):
self._variables: Dict[str, float] = {}
def set_variable(self, name: str, value: float):
"""Set a variable value in the context."""
self._variables[name] = value
def get_variable(self, name: str) -> float:
"""Get a variable value from the context."""
if name not in self._variables:
raise ValueError(f"Variable '{name}' is not defined")
return self._variables[name]
def has_variable(self, name: str) -> bool:
"""Check if a variable exists in the context."""
return name in self._variables
class Expression(ABC):
"""Abstract expression interface."""
@abstractmethod
def interpret(self, context: Context) -> float:
"""Interpret the expression and return the result."""
pass
class Number(Expression):
"""Terminal expression for numeric literals."""
def __init__(self, value: float):
self.value = value
def interpret(self, context: Context) -> float:
"""Return the numeric value."""
return self.value
def __str__(self):
return str(self.value)
class Variable(Expression):
"""Terminal expression for variables."""
def __init__(self, name: str):
self.name = name
def interpret(self, context: Context) -> float:
"""Return the variable value from context."""
return context.get_variable(self.name)
def __str__(self):
return self.name
# What we accomplished in this step:
# - Created Number class for literal numeric values
# - Created Variable class for named variables that lookup values in context
# - Both implement the Expression interface
# Step 3: Create non-terminal expressions for arithmetic operations
# ===============================================================================
# Explanation:
# Non-terminal expressions contain other expressions and perform operations on them.
# These represent the internal nodes of the expression tree.
from abc import ABC, abstractmethod
from typing import Dict, Any
class Context:
"""Context class to store variable values and state."""
def __init__(self):
self._variables: Dict[str, float] = {}
def set_variable(self, name: str, value: float):
"""Set a variable value in the context."""
self._variables[name] = value
def get_variable(self, name: str) -> float:
"""Get a variable value from the context."""
if name not in self._variables:
raise ValueError(f"Variable '{name}' is not defined")
return self._variables[name]
def has_variable(self, name: str) -> bool:
"""Check if a variable exists in the context."""
return name in self._variables
class Expression(ABC):
"""Abstract expression interface."""
@abstractmethod
def interpret(self, context: Context) -> float:
"""Interpret the expression and return the result."""
pass
class Number(Expression):
"""Terminal expression for numeric literals."""
def __init__(self, value: float):
self.value = value
def interpret(self, context: Context) -> float:
"""Return the numeric value."""
return self.value
def __str__(self):
return str(self.value)
class Variable(Expression):
"""Terminal expression for variables."""
def __init__(self, name: str):
self.name = name
def interpret(self, context: Context) -> float:
"""Return the variable value from context."""
return context.get_variable(self.name)
def __str__(self):
return self.name
class AddExpression(Expression):
"""Non-terminal expression for addition."""
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: Context) -> float:
"""Add the results of left and right expressions."""
return self.left.interpret(context) + self.right.interpret(context)
def __str__(self):
return f"({self.left} + {self.right})"
class SubtractExpression(Expression):
"""Non-terminal expression for subtraction."""
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: Context) -> float:
"""Subtract right expression from left expression."""
return self.left.interpret(context) - self.right.interpret(context)
def __str__(self):
return f"({self.left} - {self.right})"
class MultiplyExpression(Expression):
"""Non-terminal expression for multiplication."""
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: Context) -> float:
"""Multiply the results of left and right expressions."""
return self.left.interpret(context) * self.right.interpret(context)
def __str__(self):
return f"({self.left} * {self.right})"
class DivideExpression(Expression):
"""Non-terminal expression for division."""
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: Context) -> float:
"""Divide left expression by right expression."""
right_value = self.right.interpret(context)
if right_value == 0:
raise ValueError("Division by zero")
return self.left.interpret(context) / right_value
def __str__(self):
return f"({self.left} / {self.right})"
# What we accomplished in this step:
# - Created AddExpression for addition operations
# - Created SubtractExpression for subtraction operations
# - Created MultiplyExpression for multiplication operations
# - Created DivideExpression for division operations with zero-division protection
# - All non-terminal expressions contain two child expressions
# Step 4: Create a simple expression parser
# ===============================================================================
# Explanation:
# A parser helps build expression trees from string representations.
# This is a simple parser for basic arithmetic expressions.
from abc import ABC, abstractmethod
from typing import Dict, Any, List
import re
class Context:
"""Context class to store variable values and state."""
def __init__(self):
self._variables: Dict[str, float] = {}
def set_variable(self, name: str, value: float):
"""Set a variable value in the context."""
self._variables[name] = value
def get_variable(self, name: str) -> float:
"""Get a variable value from the context."""
if name not in self._variables:
raise ValueError(f"Variable '{name}' is not defined")
return self._variables[name]
def has_variable(self, name: str) -> bool:
"""Check if a variable exists in the context."""
return name in self._variables
class Expression(ABC):
"""Abstract expression interface."""
@abstractmethod
def interpret(self, context: Context) -> float:
"""Interpret the expression and return the result."""
pass
class Number(Expression):
"""Terminal expression for numeric literals."""
def __init__(self, value: float):
self.value = value
def interpret(self, context: Context) -> float:
"""Return the numeric value."""
return self.value
def __str__(self):
return str(self.value)
class Variable(Expression):
"""Terminal expression for variables."""
def __init__(self, name: str):
self.name = name
def interpret(self, context: Context) -> float:
"""Return the variable value from context."""
return context.get_variable(self.name)
def __str__(self):
return self.name
class AddExpression(Expression):
"""Non-terminal expression for addition."""
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: Context) -> float:
"""Add the results of left and right expressions."""
return self.left.interpret(context) + self.right.interpret(context)
def __str__(self):
return f"({self.left} + {self.right})"
class SubtractExpression(Expression):
"""Non-terminal expression for subtraction."""
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: Context) -> float:
"""Subtract right expression from left expression."""
return self.left.interpret(context) - self.right.interpret(context)
def __str__(self):
return f"({self.left} - {self.right})"
class MultiplyExpression(Expression):
"""Non-terminal expression for multiplication."""
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: Context) -> float:
"""Multiply the results of left and right expressions."""
return self.left.interpret(context) * self.right.interpret(context)
def __str__(self):
return f"({self.left} * {self.right})"
class DivideExpression(Expression):
"""Non-terminal expression for division."""
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: Context) -> float:
"""Divide left expression by right expression."""
right_value = self.right.interpret(context)
if right_value == 0:
raise ValueError("Division by zero")
return self.left.interpret(context) / right_value
def __str__(self):
return f"({self.left} / {self.right})"
class ExpressionParser:
"""Simple parser for arithmetic expressions."""
def __init__(self):
self.operators = {
'+': AddExpression,
'-': SubtractExpression,
'*': MultiplyExpression,
'/': DivideExpression
}
def parse(self, expression_str: str) -> Expression:
"""Parse a string expression into an Expression tree."""
# Remove spaces
expression_str = expression_str.replace(' ', '')
# Simple tokenization
tokens = self._tokenize(expression_str)
# Build expression tree (simple left-to-right evaluation)
return self._build_expression(tokens)
def _tokenize(self, expression_str: str) -> List[str]:
"""Tokenize the expression string."""
# Simple regex to split on operators while keeping them
pattern = r'([+\-*/()])'
tokens = re.split(pattern, expression_str)
return [token for token in tokens if token]
def _build_expression(self, tokens: List[str]) -> Expression:
"""Build expression tree from tokens (simplified)."""
if len(tokens) == 1:
# Single token - either number or variable
token = tokens[0]
if token.replace('.', '').replace('-', '').isdigit():
return Number(float(token))
else:
return Variable(token)
# Find the main operator (rightmost + or -, then * or /)
main_op_index = -1
for i in range(len(tokens) - 1, -1, -1):
if tokens[i] in ['+', '-']:
main_op_index = i
break
if main_op_index == -1:
for i in range(len(tokens) - 1, -1, -1):
if tokens[i] in ['*', '/']:
main_op_index = i
break
if main_op_index == -1:
raise ValueError("Invalid expression")
operator = tokens[main_op_index]
left_tokens = tokens[:main_op_index]
right_tokens = tokens[main_op_index + 1:]
left_expr = self._build_expression(left_tokens)
right_expr = self._build_expression(right_tokens)
return self.operators[operator](left_expr, right_expr)
# What we accomplished in this step:
# - Created ExpressionParser class to build expression trees from strings
# - Added tokenization to split expressions into components
# - Implemented simple expression tree building with operator precedence
# - Parser can handle numbers, variables, and basic arithmetic operations
# Step 5: Test the complete Interpreter pattern implementation
# ===============================================================================
# Explanation:
# Let's test our Interpreter pattern implementation with various expressions
# to demonstrate how it works with variables and complex expressions.
from abc import ABC, abstractmethod
from typing import Dict, Any, List
import re
class Context:
"""Context class to store variable values and state."""
def __init__(self):
self._variables: Dict[str, float] = {}
def set_variable(self, name: str, value: float):
"""Set a variable value in the context."""
self._variables[name] = value
def get_variable(self, name: str) -> float:
"""Get a variable value from the context."""
if name not in self._variables:
raise ValueError(f"Variable '{name}' is not defined")
return self._variables[name]
def has_variable(self, name: str) -> bool:
"""Check if a variable exists in the context."""
return name in self._variables
class Expression(ABC):
"""Abstract expression interface."""
@abstractmethod
def interpret(self, context: Context) -> float:
"""Interpret the expression and return the result."""
pass
class Number(Expression):
"""Terminal expression for numeric literals."""
def __init__(self, value: float):
self.value = value
def interpret(self, context: Context) -> float:
"""Return the numeric value."""
return self.value
def __str__(self):
return str(self.value)
class Variable(Expression):
"""Terminal expression for variables."""
def __init__(self, name: str):
self.name = name
def interpret(self, context: Context) -> float:
"""Return the variable value from context."""
return context.get_variable(self.name)
def __str__(self):
return self.name
class AddExpression(Expression):
"""Non-terminal expression for addition."""
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: Context) -> float:
"""Add the results of left and right expressions."""
return self.left.interpret(context) + self.right.interpret(context)
def __str__(self):
return f"({self.left} + {self.right})"
class SubtractExpression(Expression):
"""Non-terminal expression for subtraction."""
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: Context) -> float:
"""Subtract right expression from left expression."""
return self.left.interpret(context) - self.right.interpret(context)
def __str__(self):
return f"({self.left} - {self.right})"
class MultiplyExpression(Expression):
"""Non-terminal expression for multiplication."""
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: Context) -> float:
"""Multiply the results of left and right expressions."""
return self.left.interpret(context) * self.right.interpret(context)
def __str__(self):
return f"({self.left} * {self.right})"
class DivideExpression(Expression):
"""Non-terminal expression for division."""
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: Context) -> float:
"""Divide left expression by right expression."""
right_value = self.right.interpret(context)
if right_value == 0:
raise ValueError("Division by zero")
return self.left.interpret(context) / right_value
def __str__(self):
return f"({self.left} / {self.right})"
class ExpressionParser:
"""Simple parser for arithmetic expressions."""
def __init__(self):
self.operators = {
'+': AddExpression,
'-': SubtractExpression,
'*': MultiplyExpression,
'/': DivideExpression
}
def parse(self, expression_str: str) -> Expression:
"""Parse a string expression into an Expression tree."""
# Remove spaces
expression_str = expression_str.replace(' ', '')
# Simple tokenization
tokens = self._tokenize(expression_str)
# Build expression tree (simple left-to-right evaluation)
return self._build_expression(tokens)
def _tokenize(self, expression_str: str) -> List[str]:
"""Tokenize the expression string."""
# Simple regex to split on operators while keeping them
pattern = r'([+\-*/()])'
tokens = re.split(pattern, expression_str)
return [token for token in tokens if token]
def _build_expression(self, tokens: List[str]) -> Expression:
"""Build expression tree from tokens (simplified)."""
if len(tokens) == 1:
# Single token - either number or variable
token = tokens[0]
if token.replace('.', '').replace('-', '').isdigit():
return Number(float(token))
else:
return Variable(token)
# Find the main operator (rightmost + or -, then * or /)
main_op_index = -1
for i in range(len(tokens) - 1, -1, -1):
if tokens[i] in ['+', '-']:
main_op_index = i
break
if main_op_index == -1:
for i in range(len(tokens) - 1, -1, -1):
if tokens[i] in ['*', '/']:
main_op_index = i
break
if main_op_index == -1:
raise ValueError("Invalid expression")
operator = tokens[main_op_index]
left_tokens = tokens[:main_op_index]
right_tokens = tokens[main_op_index + 1:]
left_expr = self._build_expression(left_tokens)
right_expr = self._build_expression(right_tokens)
return self.operators[operator](left_expr, right_expr)
print("=== Testing Interpreter Pattern ===\n")
# Create context and set variables
context = Context()
context.set_variable("x", 10)
context.set_variable("y", 5)
context.set_variable("z", 2)
print("Variables in context:")
print(f"x = {context.get_variable('x')}")
print(f"y = {context.get_variable('y')}")
print(f"z = {context.get_variable('z')}")
print()
# Test 1: Manual expression building
print("1. Manual Expression Building:")
expression1 = AddExpression(Variable("x"), Variable("y"))
print(f"Expression: {expression1}")
print(f"Result: {expression1.interpret(context)}")
print()
# Test 2: Complex manual expression
print("2. Complex Manual Expression:")
expression2 = MultiplyExpression(
AddExpression(Variable("x"), Variable("y")),
SubtractExpression(Variable("x"), Variable("z"))
)
print(f"Expression: {expression2}")
print(f"Result: {expression2.interpret(context)}")
print()
# Test 3: Using parser for simple expressions
print("3. Using Parser for Simple Expressions:")
parser = ExpressionParser()
simple_expressions = ["x+y", "x-z", "x*y", "x/z"]
for expr_str in simple_expressions:
try:
expression = parser.parse(expr_str)
result = expression.interpret(context)
print(f"'{expr_str}' = {result}")
except Exception as e:
print(f"Error parsing '{expr_str}': {e}")
print()
# Test 4: Numeric expressions
print("4. Numeric Expressions:")
numeric_expressions = ["5+3", "10-4", "6*7", "20/4"]
for expr_str in numeric_expressions:
try:
expression = parser.parse(expr_str)
result = expression.interpret(context)
print(f"'{expr_str}' = {result}")
except Exception as e:
print(f"Error parsing '{expr_str}': {e}")
print()
# Test 5: Mixed expressions
print("5. Mixed Expressions (numbers and variables):")
mixed_expressions = ["x+5", "10-y", "z*3", "20/y"]
for expr_str in mixed_expressions:
try:
expression = parser.parse(expr_str)
result = expression.interpret(context)
print(f"'{expr_str}' = {result}")
except Exception as e:
print(f"Error parsing '{expr_str}': {e}")
print()
# Test 6: Error handling
print("6. Error Handling:")
try:
undefined_var = Variable("undefined")
undefined_var.interpret(context)
except ValueError as e:
print(f"Expected error for undefined variable: {e}")
try:
division_by_zero = DivideExpression(Number(10), Number(0))
division_by_zero.interpret(context)
except ValueError as e:
print(f"Expected error for division by zero: {e}")
# What we accomplished in this step:
# - Tested manual expression building with variables
# - Tested complex nested expressions
# - Demonstrated parser usage with simple expressions
# - Tested numeric-only expressions
# - Tested mixed expressions with numbers and variables
# - Demonstrated proper error handling for undefined variables and division by zero
# ===============================================================================
# CONGRATULATIONS!
#
# You've successfully completed the step-by-step Interpreter pattern solution!
#
# Key concepts learned:
# - Interpreter pattern structure and purpose
# - Abstract expression interface for grammar rules
# - Terminal expressions (Number, Variable) for leaf nodes
# - Non-terminal expressions (Add, Subtract, etc.) for operations
# - Context class for storing variable state
# - Expression tree building and evaluation
# - Simple parsing for string-to-expression conversion
#
# Try it yourself:
# 1. Start with Step 1 and code along
# 2. Test each step before moving to the next
# 3. Understand WHY each component is necessary
# 4. Experiment with modifications (try adding power operator!)
#
# Remember: The best way to learn is by doing!
# ===============================================================================