add postfix solns
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
from typing import (
|
||||
List,
|
||||
)
|
||||
|
||||
from collections import deque
|
||||
|
||||
class Solution:
|
||||
"""
|
||||
@param expression: A string array
|
||||
@return: The Reverse Polish notation of this expression
|
||||
"""
|
||||
def convert_to_r_p_n(self, expression: List[str]) -> List[str]:
|
||||
op_priority = {
|
||||
'/': 1 << 4,
|
||||
'*': 1 << 4,
|
||||
'+': 1 << 2,
|
||||
'-': 1 << 2,
|
||||
'(': 1 << 0
|
||||
}
|
||||
|
||||
op_stack = deque()
|
||||
result = []
|
||||
|
||||
for token in expression:
|
||||
if token.isdigit():
|
||||
result.append(token)
|
||||
|
||||
elif token == '(':
|
||||
op_stack.append(token)
|
||||
|
||||
elif token == ')':
|
||||
while len(op_stack) > 0 and op_stack[-1] != '(':
|
||||
result.append(op_stack.pop())
|
||||
|
||||
op_stack.pop()
|
||||
|
||||
else:
|
||||
# For any other operator, keep popping and appending to results as long as there
|
||||
# are higher priority operators in the stack
|
||||
while len(op_stack) > 0 and op_priority[op_stack[-1]] >= op_priority[token]:
|
||||
result.append(op_stack.pop())
|
||||
|
||||
op_stack.append(token)
|
||||
|
||||
# Pop and append the remaining operators in the stack
|
||||
while len(op_stack) > 0:
|
||||
result.append(op_stack.pop())
|
||||
|
||||
return result
|
||||
Reference in New Issue
Block a user