diff --git a/evaluate.py b/evaluate.py index a024cea..ea14c5e 100644 --- a/evaluate.py +++ b/evaluate.py @@ -18,8 +18,8 @@ def convert_to_num(entry): - @staticmethod - def _apply_binary_op(op, a, b): + + def _apply_binary_op(self, op, a, b): if op == "+": return a + b elif op == "-": @@ -31,6 +31,7 @@ def _apply_binary_op(op, a, b): elif op == "^": return a**b elif op == "mod": + b = self.convert_to_num(b) if isinstance(b, float): #! check if there is a float number after the mod raise Exception("Syntax error: 'mod' requires an integer operand") diff --git a/main.py b/main.py index 2f002a1..d493d6c 100644 --- a/main.py +++ b/main.py @@ -3,7 +3,6 @@ from evaluate import Evaluate import matplotlib.pyplot as plt import numpy as np - from symbol_table import SymbolTable @@ -94,9 +93,6 @@ def main(file_name): parser = Parser(symbol_table, tokens) parser.parse() - - - while True: print("1- Without visual") print("2- With visual") @@ -107,7 +103,12 @@ def main(file_name): if choice == "1": print("Parsed postfix expression:") for i in parser.postfix: - print(i.value, end=" ") + if i.value == 'unary-': + print('-') + elif i.value == 'unary+': + print('+') + else: + print(i.value, end=" ") print("\n") evaluate = Evaluate(parser.postfix,symbol_table) print(evaluate.evaluate()) @@ -131,4 +132,4 @@ def main(file_name): if __name__ == "__main__": - main('test.txt') + main('input1.txt') diff --git a/parser.py b/parser.py index d5c7c1d..96ee05c 100644 --- a/parser.py +++ b/parser.py @@ -93,7 +93,7 @@ def term_prime(self): self.match('mod') - if self.lookahead.type not in {"ID", "NUM"} or '.' in self.lookahead.value: + if self.lookahead.type not in {"ID", "NUM", "FUNCTION"} or '.' in self.lookahead.value: raise Exception(f"Syntax error at Line {self.lookahead.line}: 'mod' requires an integer operand") diff --git a/symbol_table.py b/symbol_table.py index 73acd10..115a0f8 100644 --- a/symbol_table.py +++ b/symbol_table.py @@ -1,5 +1,6 @@ +import math class SymbolTable: - #! variables , functions , + # * inside the lexical analyzer when it hits to a ID it creates an entry for it def __init__(self): self.table = { @@ -15,6 +16,7 @@ def __init__(self): '(': {'type': 'DELIMITER', "is_reserved": None}, ')': {'type': 'DELIMITER', "is_reserved": None}, 'e': {'type': 'IDENTIFIER', 'value': 2.71, "is_reserved": True}, + 'pi': {'type': 'IDENTIFIER', 'value': math.pi, "is_reserved": True}, 'sin': {'type': 'FUNCTION', 'args': 1, "is_reserved": True}, 'cos': {'type': 'FUNCTION', 'args': 1, "is_reserved": True}, 'tan': {'type': 'FUNCTION', 'args': 1, "is_reserved": True},