标签:class == code ota bre 数组 pop eve pen
很多笔试题都会问中序表达式转换成后缀表达式的方法
算法很固定,需要用到两个栈
想将表达式字符串转换成tokens,然后在从左向右遍历整个数组。
def reverse_polish_notation(expression:str): op_stack = [] digit_stack = [] expression = tokenize(expression) print(expression) for n in expression: if n.isdigit(): digit_stack.append(n) elif n in "+-*/": while True: if len(op_stack) == 0 or op_stack[-1] == ‘(‘: op_stack.append(n) break elif getValue(op_stack[-1]) < getValue(n): op_stack.append(n) break else: op = op_stack.pop() digit_stack.append(op) else: if n == ‘(‘: op_stack.append(n) elif n == ‘)‘: is_pair = False while len(op_stack) > 0: op = op_stack.pop() if op == ‘(‘: is_pair = True break else: digit_stack.append(op) if not is_pair: return [] while len(op_stack) > 0: op = op_stack.pop() digit_stack.append(op) return digit_stack def getValue(op:str): if op == ‘*‘ or op == ‘/‘: return 2 elif op == ‘+‘ or op == ‘-‘: return 1 return ord(op) def tokenize(expression:str): res = [] token = "" for i in range(len(expression)): if expression[i] in ‘+-*/()‘: if len(token) > 0 and token[0].isdigit(): res.append(token) token = "" else: res.append(expression[i]) else: token += expression[i] if token != "": res.append(token) return res if __name__ == "__main__": res = reverse_polish_notation("1+((23+3)*4)-5") print("".join(res))
标签:class == code ota bre 数组 pop eve pen
原文地址:https://www.cnblogs.com/AcodingDg/p/12450820.html