Created
April 25, 2024 17:51
-
-
Save amabirbd/ffa151930e1c1568a639b5ab66176f4f to your computer and use it in GitHub Desktop.
Python program for solving equation
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
from collections import deque | |
def precedence(op): | |
"""Returns the precedence of an operator.""" | |
if op in "+-": | |
return 1 | |
elif op in "*/": | |
return 2 | |
else: | |
return 0 | |
def execute(op, operand1, operand2): | |
"""Executes a binary operation.""" | |
if op == "+": | |
return operand1 + operand2 | |
elif op == "-": | |
return operand1 - operand2 | |
elif op == "*": | |
return operand1 * operand2 | |
elif op == "/": | |
return operand1 / operand2 | |
else: | |
raise ValueError("Invalid operator") | |
def tokenize_equation(equation): | |
"""Tokenizes the equation string into a list of tokens.""" | |
tokens = [] | |
current_token = '' | |
for char in equation: | |
# print("char: ", char) | |
if char.isdigit() or char == '.': | |
current_token += char | |
elif char in '+-*/()': | |
if current_token: | |
tokens.append(current_token) | |
current_token = '' | |
tokens.append(char) | |
elif char == ' ': | |
if current_token: | |
tokens.append(current_token) | |
current_token = '' | |
else: | |
raise ValueError(f"Invalid character: {char}") | |
if current_token: | |
tokens.append(current_token) | |
print("tokens: ", tokens) | |
return tokens | |
def parse_infix_to_postfix(tokenized_equation): | |
"""Converts infix expression to postfix using a stack and queue.""" | |
tokens = tokenized_equation | |
postfix = deque() | |
operator_stack = [] | |
for token in tokens: | |
if token.replace('.', '', 1).isdigit(): | |
postfix.append(float(token)) | |
elif token in "+-*/": | |
while operator_stack and precedence(operator_stack[-1]) >= precedence(token): | |
postfix.append(operator_stack.pop()) | |
operator_stack.append(token) | |
elif token == "(": | |
operator_stack.append(token) | |
elif token == ")": | |
while operator_stack and operator_stack[-1] != "(": | |
postfix.append(operator_stack.pop()) | |
if not operator_stack: | |
raise ValueError("Missing opening parenthesis") | |
operator_stack.pop() # Remove the opening parenthesis | |
else: | |
raise ValueError(f"Invalid token: {token}") | |
while operator_stack: | |
postfix.append(operator_stack.pop()) | |
print("postfix: ", postfix) | |
return postfix | |
def evaluate_postfix(postfix): | |
"""Evaluates the postfix expression using a stack.""" | |
operand_stack = [] | |
for token in postfix: | |
if isinstance(token, float): | |
operand_stack.append(token) | |
else: | |
operand2 = operand_stack.pop() | |
operand1 = operand_stack.pop() | |
result = execute(token, operand1, operand2) | |
operand_stack.append(result) | |
if len(operand_stack) != 1: | |
raise ValueError("Invalid postfix expression") | |
return operand_stack.pop() | |
def solve(equation): | |
"""Solves the equation by converting it to postfix and then evaluating it.""" | |
tokenized_equation = tokenize_equation(equation) | |
# print(tokenized_equation) | |
postfix = parse_infix_to_postfix(tokenized_equation) | |
return evaluate_postfix(postfix) | |
# Example usage | |
equation = "(3 + 3) * 4" | |
result = solve(equation) | |
print(f"Equation: {equation}") | |
print(f"Result: {result}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment