On python please # Code the function mask(s) as discussed in class # - You can a
ID: 3858874 • Letter: O
Question
On python please
# Code the function mask(s) as discussed in class
# - You can assume s is an error-free arithmetic expression
# - The first non-space char of s is not "-"
# - It returns s any charactor of inside a parentheses pair
# is replaced by space
# - no change of the class and funciton names
class expressionTree:
# constructTree(expr) builds the expression tree from expr
# Here you can assume:
# expr is an arithmetic expression with an answer value
# The first non-space symbol is not "-"
# (because we can add "0" to the left if so)
#
# getExpr() to reconstruct expr from the tree
#
# revPolish() to get the reverse polish notatation
#
# and maybe more...
class treeNode:
def __init__(self, value, lchild, rchild):
self.value, self.lchild, self.rchild = value, lchild, rchild
def __init__(self):
self.treeRoot = None
def mask(self, s):
# The function empties the inside of every outermost parentheses pair
# and return it as a string
#
# e.g. s = ( 2 + 3^2 -(2-4)) + 2 - (-1 + 1/7)
# It returns ( ) + 2 - ( )
#
# --- code ----#
# To check the mask function
e = expressionTree()
s =" ( 2 + 3*(2- 1/3))+ 2 - ((5-2/3)*3 - 2)"
print(e.mask(s))
# should print
# ( )+ 2 - ( )
Explanation / Answer
class expressionTree:
# constructTree(expr) builds the expression tree from expr
# Here you can assume:
# expr is an arithmetic expression with an answer value
# The first non-space symbol is not "-"
# (because we can add "0" to the left if so)
#
# getExpr() to reconstruct expr from the tree
#
# revPolish() to get the reverse polish notatation
#
# and maybe more...
class treeNode:
def __init__(self, value, lchild, rchild):
self.value, self.lchild, self.rchild = value, lchild, rchild
def __init__(self):
self.treeRoot = None
def mask(self, sin):
count = 0# count of open brackets
s = ""# this string contains the answer
flag = 0# declare a flag for outermost brackets
for c in sin:
if c == "(":
count += 1 #increment count of open brackets
if count == 1: # if the outermost bracket then add it to s
flag = 1
s+=c
else:# else add space
s+=" "
elif c == ")":# decrement count for each close bracket
count -= 1
if count == 0:# if the outermost bracket then add it to s
flag=0
s+=c
else:# else add space
s+=" "
else:
if flag == 1:# inside bracket then add space
s+=" "
else:
s+=c# add it to s
return s
# The function empties the inside of every outermost parentheses pair
# and return it as a string
#
# e.g. s = ( 2 + 3^2 -(2-4)) + 2 - (-1 + 1/7)
# It returns ( ) + 2 - ( )
#
# --- code ----#
# To check the mask function
e = expressionTree()
s =" ( 2 + 3*(2- 1/3))+ 2 - ((5-2/3)*3 - 2)"
print(e.mask(s))
# should print
# ( )+ 2 - ( )
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.