You are on page 1of 3

EX 7: BODMAS Conversion and Evaluation

Get a complex expression from the user in human‘s understandable BODMAS format
and convert the same expression into machine readable form.
ALGORITHM:
Input: None (user interaction for input)
Output: Result of the evaluated expression
1. Define a function convert_to_machine_readable(expression) to convert a human-readable
expression to a machine-readable form.
a. Replace '×' with '*' in the expression.
b. Replace '÷' with '/' in the expression.
c. Replace '−' with '-' in the expression.
d. Use regular expressions to add explicit multiplication:
- Add '*' after a number and before an opening bracket.
- Add '*' before a closing bracket.
- Add '*' between a number and an operator.
e. Remove spaces around multiplication operators.

2. Define a function evaluate_expression(expression) to evaluate a machine-readable


expression.
a. Use the eval() function to evaluate the expression.
b. Catch any exceptions and return an error message if evaluation fails.

3. Main program:
a. Get a complex expression in BODMAS format from the user.
b. Call convert_to_machine_readable() with the user-input expression to obtain the
machine-readable expression.
c. Print the machine-readable expression.
d. Call evaluate_expression() with the machine-readable expression to obtain the result.
e. Print the result.

4. Example usage:
a. Call the main program to execute the conversion and evaluation.
PROGRAM:
import re

def convert_to_machine_readable(expression):
# Replace human-readable operators with machine-readable ones
expression = expression.replace('×', '*').replace('÷', '/').replace('−', '-')

# Convert the expression into a format suitable for evaluation


expression = re.sub(r'(?<=[0-9)])\(', '*(', expression) # Add explicit multiplication after a
number and before an opening bracket
expression = re.sub(r'(?<![0-9)])\)', ')*', expression) # Add explicit multiplication before a
closing bracket
expression = re.sub(r'(?<=[0-9])[^+\-*/()]', '*\g<0>', expression) # Add explicit
multiplication between a number and an operator

# Remove spaces around multiplication operators


expression = re.sub(r'\s*\*\s*', '*', expression)

return expression

def evaluate_expression(expression):
try:
result = eval(expression)
return result
except Exception as e:
return f"Error: {str(e)}"

# Example usage:
human_expression = input("Enter a complex expression in BODMAS format: ")
machine_readable_expression = convert_to_machine_readable(human_expression)
print("Machine-readable expression:", machine_readable_expression)

result = evaluate_expression(machine_readable_expression)
print("Result:", result)

OUTPUT:
Enter a complex expression in BODMAS format: (5+3)*(7-2)/4
Machine-readable expression: (5+3)*(7-2)/4
Result: 10.0

You might also like