Great Deal! Get Instant $10 FREE in Account on First Order + 10% Cashback on Every Order Order Now

Please complete this assignment and submit in a python file, name it p5.py and implement expression evaluator using Python. The input text files t5*.dat should be at the same directory with your p5.py...

1 answer below »
Please complete this assignment and submit in a python file, name it p5.py and implement expression evaluator using Python. The input text files t5*.dat should be at the same directory with your p5.py file. Each input file has only one expression consists of positive integers, whitespaces like space (‘ ‘) or tab, add (‘+’), multiply (‘*’), open parenthesis (‘(‘), and close parenthesis (‘)’). If input contains any other characters or imbalanced open and close parenthesis, your p5 should report e
or and handle the next input file if there is one. The parenthesis has the highest precedence, the * is second highest, and + is the lowest. Since you read input as a character string, you need to convert numbers to integer by int(). If the input is a legal expression, your p5 should output co
ect answer for the expression.
 
Example input and output:
t50.dat:
2*(5+3*3)
The output for t50.dat should be 28
t51.dat:
(1 + 2 * (51              + 3 * 3)) * XXXXXXXXXX
The output for t51 should be 1562
t59.dat:
(1+a)) + 1 * ((2)
Your p5 should report e
or and handle next input file.
Answered Same Day Sep 25, 2021

Solution

Sanghamitra answered on Sep 27 2021
143 Votes
66339/p5.py
import os
import math
#change the path
directory = r'C:\Users\HP\Downloads\66339'
ALLOWED_NAMES = {
k: v for k, v in math.__dict__.items() if not k.startswith("__")
}
# Function to convert list to string
def listToString(s):
# initialize an empty string
str1 = ""
# traverse in the string
for ele in s:
str1 += ele
# return string
return str1
def evaluate(expression):
"""Evaluate a math expression."""
code = compile(expression, "", "eval")
# Validate allowed names
for name in code.co_names:
if name not in ALLOWED_NAMES:
raise NameE
or(f"The use of '{name}' is not allowed")
#...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here