n | class ExpressionCalculator: | n | class Calculator: |
| | | |
| def __init__(self): | | def __init__(self): |
n | self.storage = {} | n | self.variables = {} |
| self.safe_env = {'__builtins__': {}} | | self.allowed_namespaces = {'__builtins__': {}} |
| | | |
n | def handle_input(self, command): | n | def process_input(self, line): |
| command = command.strip() | | line = line.strip() |
| if not command or command.startswith('#'): | | if not line or line.startswith('#'): |
| return None | | return None |
n | if '=' in command: | n | if '=' in line: |
| variable, expression = map(str.strip, command.split('=', 1)) | | identifier, expr = map(str.strip, line.split('=', 1)) |
| return self.set_variable(variable, expression) | | return self.assign(identifier, expr) |
| return self.evaluate(command) | | return self.evaluate_expression(line) |
| | | |
n | def set_variable(self, variable, expression): | n | def assign(self, identifier, expr): |
| if not variable.isidentifier(): | | if not identifier.isidentifier(): |
| return 'Assignment error' | | return 'Assignment error' |
| try: | | try: |
n | self.storage[variable] = eval(expression, self.safe_env, sel | n | self.variables[identifier] = eval(expr, self.allowed_namespa |
| f.storage) | | ces, self.variables) |
| except SyntaxError: | | except SyntaxError: |
| return 'Syntax error' | | return 'Syntax error' |
| except NameError: | | except NameError: |
| return 'Name error' | | return 'Name error' |
| except Exception: | | except Exception: |
| return 'Runtime error' | | return 'Runtime error' |
| return None | | return None |
| | | |
n | def evaluate(self, expression): | n | def evaluate_expression(self, expr): |
| try: | | try: |
n | result = eval(expression, self.safe_env, self.storage) | n | result = eval(expr, self.allowed_namespaces, self.variables) |
| return result | | return result |
| except SyntaxError: | | except SyntaxError: |
| return 'Syntax error' | | return 'Syntax error' |
| except NameError: | | except NameError: |
| return 'Name error' | | return 'Name error' |
| except Exception: | | except Exception: |
| return 'Runtime error' | | return 'Runtime error' |
n | calc = ExpressionCalculator() | n | calculator = Calculator() |
| while True: | | while True: |
n | cmd = input().strip() | n | line = input().strip() |
| if not cmd: | | if not line: |
| break | | break |
t | output = calc.handle_input(cmd) | t | result = calculator.process_input(line) |
| if output is not None: | | if result is not None: |
| print(output) | | print(result) |