class Solution:
def evalRPN(self, tokens: List[str]) -> int:
f1 = lambda x,y:x+y
f2 = lambda x,y:x-y
f3 = lambda x,y:x*y
f4 = lambda x,y:int(x/y)
dic = {'+':f1,'-':f2,'*':f3,'/':f4}
stack = []
for i in tokens:
if i in dic:
x, y = stack.pop(),stack.pop()
stack.append(dic[i](y,x))
else:
stack.append(int(i))
print(stack)
return stack[-1]
- Topic analysis
- Given a character number group, which contains addition, subtraction, multiplication and division
- Define 4 functions with lambda in advance, and map them to the hash table according to the operation symbols
- If it is a number directly into the stack, if it is not a number, then pop out the stack for calculation, and then push the result of the calculation into the stack