- #1
FallArk
- 127
- 0
My instructor gave out a sample code as listed below:
What I have to do is to implement the algorithm. My instructor did not mention any basics of python in class other than telling me
starts a function. The way I was thinking about implementing this algorithm is that when given something like
, the function
Code:
def eval_infix_sum(expr, pos):
"""evaluate a sum expression (zero or more additions and subtractions)
expr Python string list complete expression to be evaluated
pos integer subscript to current token
"""
... implementation of algorithm above
return ans, pos # return result and updated subscript
def eval_infix_product(expr, pos):
"""evaluate a product expression (zero or more multiplications/divisions)
# NOTE: This must be extended to support parenthesized sub-expressions)
def eval_infix_factor( expr, pos ):
"""evaluate a factor (number or parenthesized sub-expression)
return int(expr[pos]), pos+1 # convert string to int, and move past
# the following functions are defined to supply a 'friendlier' interface to the clients,
# which will later also be used to provide some degree of implementation hiding.
def eval_infix_list(expr):
"""evaluate an expression represented as a list of strings
ans, discard = eval_infix_sum( expr, 0 ) # start subscript at 0, then forget it
return ans
def eval_infix(expr):
"""evaluate an expression represented as a single space-separated string
return eval_infix_list(expr.split() + [ ";"]) # make a list, and append semicolon
Code:
def
Code:
eval_infix_product( [ "2","*","3",";" ], 0)
will check each element inside the list and decide if it is a division or multiplication, however, I do not really know how to write this in python. Could someone explain this and help me?eval_infix_product