1 Star 0 Fork 2

武斌/SmartEdu_1

forked from Akai_akari/SmartEdu 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
carculate.py 2.22 KB
一键复制 编辑 原始数据 按行查看 历史
class Calculator:
def __init__(self):
pass
@staticmethod
def infix_to_postfix(expression: list[str]):
stack = []
output = []
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
for token in expression:
if token.isnumeric():
output.append(token)
elif token == '(':
stack.append(token)
elif token == ')':
while stack and stack[-1] != '(':
output.append(stack.pop())
stack.pop() # 弹出左括号
else:
while stack and stack[-1] != '(' and precedence[token] <= precedence.get(stack[-1], 0):
output.append(stack.pop())
stack.append(token)
while stack:
output.append(stack.pop())
return output
@staticmethod
def calculate_postfix(expression: list[str]):
stack = []
for token in expression:
if token.isnumeric():
stack.append(int(token))
else:
operand2 = stack.pop()
operand1 = stack.pop()
result = 0
if token == '+':
result = operand1 + operand2
elif token == '-':
result = operand1 - operand2
elif token == '*':
result = operand1 * operand2
elif token == '/':
result = operand1 / operand2
stack.append(result)
return stack.pop()
@staticmethod
def str_to_list(equation: str):
res = []
curOp = ''
for _chr in equation:
if '0' <= _chr <= '9':
curOp += _chr
else:
if len(curOp) > 0:
res.append(curOp)
curOp = ''
res.append(_chr)
if len(curOp) > 0:
res.append(curOp)
return res
@staticmethod
def calculate(equation: str):
return Calculator.calculate_postfix(Calculator.infix_to_postfix(Calculator.str_to_list(equation)))
def main():
test = Calculator()
print(test.calculate('(2+3)*4-5+6'))
if __name__ == '__main__':
main()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/guai128/smart-edu_1.git
[email protected]:guai128/smart-edu_1.git
guai128
smart-edu_1
SmartEdu_1
master

搜索帮助