代码拉取完成,页面将自动刷新
同步操作将从 Akai_akari/SmartEdu 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
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()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。