Created
February 28, 2020 15:35
-
-
Save Tran-Antoine/80942fd0ced23bbdf1831f47f6fea8ef to your computer and use it in GitHub Desktop.
Simple programm to evaluate expressions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Branch: | |
| def __init__(self, value): | |
| self.value = value | |
| self.operation = None | |
| self.left = None | |
| self.right = None | |
| self.split() | |
| self.simplified_result = self.eval_branch() | |
| def split(self): | |
| for operations in (('+', '-'), ('*', '/'), ('^')): | |
| index = len(self.value) - 1 | |
| for char in self.value[::-1]: | |
| if char in operations: | |
| self.operation = char | |
| self.left = Branch(self.value[:index]) | |
| self.right = Branch(self.value[index+1:]) | |
| return | |
| index -= 1 | |
| def eval_branch(self): | |
| op = self.operation | |
| left = self.left | |
| right = self.right | |
| if op == None: | |
| return float(self.value) | |
| elif op == '+': | |
| return left.simplified_result + right.simplified_result | |
| elif op == '-': | |
| return left.simplified_result - right.simplified_result | |
| elif op == '*': | |
| return left.simplified_result * right.simplified_result | |
| elif op == '/': | |
| return left.simplified_result / right.simplified_result | |
| elif op == '^': | |
| return left.simplified_result ** right.simplified_result | |
| def __str__(self): | |
| return f"Value : {self.value}\nSimplified result: {self.simplified_result}\n" \ | |
| f"Operation: {self.operation}\nLeft member: {self.left}\nRight member: {self.right}\n\n" | |
| my_branch = Branch("3+2*4^4-5/28") | |
| print(my_branch) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment