蓝桥杯 算法训练 表达式计算 (python实现)

class Stack(object) :
    # 初始化栈为空列表
    def __init__(self):
        self.items = []

    # 判断栈是否为空,返回 True 或 False
    def is_empty(self):
        return self.items == []

    # 压栈,添加新元素进栈
    def push(self,item):
        self.items.append(item)

    # 出栈,删除栈顶元素,并返回
    # 注:列表的pop()方法用于根据索引删除并返回被删除的元素,没有传入索引参数,默认删除最后一个元素
    def pop(self):
        return self.items.pop()

    # 返回栈顶元素
    def peek(self):
        return self.items[len(self.items)-1]

    # 返回栈的大小
    def size(self):
        return len(self.items)

def compare(op1,op2) :
    '''
    比较两个运算符的优先级,乘除运算优先级比加减高
    op1优先级比op2高返回True,否则返回False
    '''
    return op1 in ["*","/"] and op2 in ["+","-"]

# 中缀表达式转化为后缀表达式
s = input()
stack_opt = Stack()
i = 0
temp_expression = ''
while i < len(s) :
    if s[i].isdigit() :
        start = i
        while i + 1 < len(s) and s[i + 1].isdigit():
            i += 1
        temp_expression += s[start:i+1] + " "
    elif stack_opt.size() == 0 or stack_opt.peek() == "(" :
        stack_opt.push(s[i])

    elif s[i] == "(" or compare(s[i],stack_opt.peek()):
        stack_opt.push(s[i])

    elif s[i] == ")" :
        while stack_opt.peek() != "(" :
            temp_expression += stack_opt.pop() + " "
        stack_opt.pop() # 左括号出栈
    else :
        while stack_opt.size() != 0 and not compare(s[i],stack_opt.peek()) :
            if stack_opt.peek() == "(" :
                break
            temp_expression += stack_opt.pop() + " "
        stack_opt.push(s[i])
    i += 1
while stack_opt.size() :
    temp_expression += stack_opt.pop() + " "

def calculate(num1,num2,operator) :
    if operator == "+" :
        return int(num1) + int(num2)
    elif operator == "-" :
        return int(num1)  - int(num2)
    elif operator == "*" :
        return int(num1)  * int(num2)
    else :
        return int(num1)  / int(num2)

def process(data,operator) :
    num2 = data.pop()
    num1 = data.pop()
    data.push(calculate(num1,num2,operator))

nums = Stack()
j = 0
while j < len(temp_expression) :
    if temp_expression[j].isdigit() :
        start = j
        while j + 1 < len(temp_expression) and temp_expression[j + 1].isdigit():
            j += 1
        nums.push(temp_expression[start:j+1])
    elif not temp_expression[j].isspace() :
        process(nums,temp_expression[j])
    j += 1
    
print(nums.pop())

评测结果:
评测结果
来看详细解说:python实现栈及栈在四则运算中的应用

你可能感兴趣的:(蓝桥杯,python,栈,stack,列表)