Certainly! Here is a compact Python code that solves complex mathematical expressions step by step. This code handles basic arithmetic operations (+, -, *, /) and supports parentheses for operations' ordering. Keep in mind, crafting a solution that exhaustively demonstrates each step for complex expressions while staying under 200 lines is a balancing act between functionality and simplicity.
This example uses a simple approach of recursive descent parsing, which is quite effective for evaluating expressions in arithmetic and programming languages. Although there are libraries like SymPy that can solve complex expressions with steps, creating something from scratch offers great learning insights:
class ExpressionSolver:
def __init__(self, expression):
self.expression = expression.replace(" ", "")
self.index = 0
def next_char(self):
return self.expression[self.index] if self.index < len(self.expression) else None
def eat(self, char_to_eat):
if self.next_char() == char_to_eat:
self.index += 1
return True
return False
def parse(self):
result = self.parse_expression()
if self.index < len(self.expression):
raise ValueError("Unexpected character found: " + self.next_char())
return result
def parse_expression(self):
results = [self.parse_term()]
while True:
if self.eat('+'):
print(f"{results[-1]} + ", end="")
results.append(self.parse_term())
results[-2] += results.pop() # Add the last two results
elif self.eat('-'):
print(f"{results[-1]} - ", end="")
results.append(-self.parse_term())
results[-2] += results.pop() # Add the last two results (with the second negated)
else:
return results[0]
def parse_term(self):
results = [self.parse_factor()]
while True:
if self.eat('*'):
print(f"{results[-1]} * ", end="")
results.append(self.parse_factor())
results[-2] *= results.pop() # Multiply the last two results
elif self.eat('/'):
print(f"{results[-1]} / ", end="")
denominator = self.parse_factor()
if denominator == 0:
raise ValueError("Division by zero")
results.append(denominator)
results[-2] /= results.pop() # Divide the last two results
else:
return results[0]
def parse_factor(self):
if self.eat('+'):
return self.parse_factor() # Unary plus
if self.eat('-'):
return -self.parse_factor() # Unary minus
start_index = self.index
if self.eat('('): # Parentheses
result = self.parse_expression()
if not self.eat(')'):
raise ValueError("Missing closing parenthesis")
print(f"({result})", end="")
return result
while self.next_char() is not None and self.next_char().isdigit():
self.index += 1
number = self.expression[start_index:self.index]
if not number:
raise ValueError("Unexpected character: " + self.next_char())
return float(number)
def solve_expression(expression):
try:
solver = ExpressionSolver(expression)
result = solver.parse()
print(f" = {result}")
return result
except ValueError as e:
print(e)
return None
# Example usage:
solve_expression("4 + 18/(9-3)")
This builds a very basic evaluator for expressions with steps shown in the calculation process. The script prints the steps and results of arithmetic operations processed. For more advanced mathematical operations (such as exponentiation, trigonometry, logarithms, etc.), complex parser development, or additional libraries would be necessary.
This code is kept simple to introduce the concept. Enhancements like adding more operations or improving error handling would make the evaluator robust but might exceed the 200-line limit.