add postfix solns

This commit is contained in:
2022-04-13 04:55:09 +05:30
parent 658601137a
commit e91751a4ce
4 changed files with 129 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
Given a string array representing an expression, and return the Reverse Polish notation of this expression. (remove the parentheses)
Definition of _Reverse Polish Notation_:
* [https://en.wikipedia.org/wiki/Reverse\_Polish\_notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation)
Example
Example 1:
Input: ["3", "-", "4", "+", "5"] Output: ["3", "4", "-", "5", "+"] Explanation: 3 - 4 + 5 = -1 + 5 = 4 3 4 - 5 + = -1 5 + = 4
Example 2:
Input: ["(", "5", "-", "6", ")", "*", "7"] Output: ["5","6","-","7","*"] Explanation: (5 - 6) * 7 = -1 * 7 = -7 5 6 - 7 * = -1 7 * = -7

View File

@@ -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