Professional Documents
Culture Documents
Ex 7
Ex 7
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.
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('−', '-')
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