Python Main focus on stack. Result should look like this: The Reverse Polish Not
ID: 3587920 • Letter: P
Question
Python
Main focus on stack.
Result should look like this:
The Reverse Polish Notation is "19 2.14 + 4.5 2 4.3 / - &"
The result is 85.29744186046511
def evalTokens (tokens): # Evaluate RPN expression in 'tokens' stack # Put your code here (note: you will get error "pop from emply list" # if you just run the template without putting something in stack) return stack.pop 0 rp3 1" rpn- "19 2.14 + 4.5 2 4.3 / - *" # Infix: (19 + 2.14) * (4.5-2 / 4.3); answer-85.29 # Test this first; make sure your answer is 2 and not-2 rpn_tokens.split("" resultstr (evalTokens (rpn_tokens)) print( 'The Reverse Polish Noation is " ' + rpn + '''') print( 'The result is ' + result) # should be 85.29744186046511 for above test lineExplanation / Answer
def evalTokens(tokens):
stack = []
operators = "+-*/"
for t in tokens:
if not t in operators:
stack.append(t)
else:
a = stack.pop()
b = stack.pop()
stack.append(str(eval(b + t + a)))
return stack.pop()
rpn = "19 2.14 + 4.5 2 4.3 / - *"
rpn_tokens = rpn.split(" ")
result = str(evalTokens(rpn_tokens))
print('The Reverse Polish Notation is "' + rpn + '"')
print('The result is ' + result)
# code link: https://paste.ee/p/ck7M6
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.