-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvaluate Reverse Polish Notation.py
65 lines (45 loc) · 1.92 KB
/
Evaluate Reverse Polish Notation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# https://leetcode.com/problems/evaluate-reverse-polish-notation
class Solution:
def findOperand(self, tokens):
# Define a list of operands
operandsStr=list("+ - * / ")
# Iterate tokens
for idx, i in enumerate(tokens):
if i in operandsStr:
return idx
# If there are no more operands, return -1
return -1
def calculate(self, tokens, num1, operator, num2):
# Decide on operation
if operator == "+":
return int(num1) + int(num2)
elif operator == "-":
return int(num1) - int(num2)
elif operator == "*":
return int(num1) * int(num2)
elif operator == "/":
return int(num1) / int(num2)
def evalRPN(self, tokens: List[str]) -> int:
# If tokens only has a single digit, return it
if len(tokens) == 1 and tokens[0].isnumeric():
return int(tokens[0])
# Iterate tokens until it only has 1 element
while len(tokens) > 1:
# Find first operator
firstOperandIdx = self.findOperand(tokens)
operator = tokens[firstOperandIdx]
# Get 2 numbers before operator's index
""" E.g.
Token: [3, 4, +]
num1 will be 3 and num2 will be 4.
"""
num1 = tokens[firstOperandIdx - 2]
num2 = tokens[firstOperandIdx - 1]
# Perform calculations
tmpCalculation = self.calculate(tokens, num1, operator, num2)
# Update value at index num1
tokens[firstOperandIdx - 2] = tmpCalculation
# Remove elements at operator's and num2's index
tokens.pop(firstOperandIdx)
tokens.pop(firstOperandIdx - 1)
return int(tokens[0])