-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathex01.py
More file actions
29 lines (22 loc) · 788 Bytes
/
Copy pathex01.py
File metadata and controls
29 lines (22 loc) · 788 Bytes
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
import ast
class SimpleInterpreter(ast.NodeVisitor):
def __init__(self):
self.result = 0
def visit_BinOp(self, node):
left = self.visit(node.left)
right = self.visit(node.right)
if isinstance(node.op, ast.Add):
return left + right
elif isinstance(node.op, ast.Sub):
return left - right
else:
raise ValueError(f"Unsupported operation: {type(node.op)}")
def visit_Num(self, node):
return node.n
def interpret(self, code):
tree = ast.parse(code)
return self.visit(tree.body[0].value)
if __name__ == '__main__':
# Тестуємо інтерпретатор
interpreter = SimpleInterpreter()
print(interpreter.interpret("3 + 2")) # Виведе: 6