網站首頁 編程語言 正文
python:實現利用stack對輸入的式子進行計算算法
__author__ = "Alexander Joslin"
import operator as op
from .stack import Stack
def dijkstras_two_stack_algorithm(equation: str) -> int:
"""
DocTests
>>> dijkstras_two_stack_algorithm("(5 + 3)")
8
>>> dijkstras_two_stack_algorithm("((9 - (2 + 9)) + (8 - 1))")
5
>>> dijkstras_two_stack_algorithm("((((3 - 2) - (2 + 3)) + (2 - 4)) + 3)")
-3
:param equation: a string
:return: result: an integer
"""
operators = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub}
operand_stack: Stack[int] = Stack()
operator_stack: Stack[str] = Stack()
for i in equation:
if i.isdigit():
# RULE 1
operand_stack.push(int(i))
elif i in operators:
# RULE 2
operator_stack.push(i)
elif i == ")":
# RULE 4
opr = operator_stack.peek()
operator_stack.pop()
num1 = operand_stack.peek()
operand_stack.pop()
num2 = operand_stack.peek()
operand_stack.pop()
total = operators[opr](num2, num1)
operand_stack.push(total)
# RULE 5
return operand_stack.peek()
if __name__ == "__main__":
equation = "(5 + ((4 * 2) * (2 + 3)))"
# answer = 45
print(f"{equation} = {dijkstras_two_stack_algorithm(equation)}")
原文鏈接:https://blog.csdn.net/it_xiangqiang/article/details/125898477
相關推薦
- 2023-10-12 react函數式組件的useEffect
- 2022-02-05 Tableau中如何將兩個數據源的數據進行關聯(數據混合)?
- 2022-10-11 云服務器搭建redis主從復制以及哨兵模式(附踩坑記錄)
- 2022-03-27 Python編程入門指南之函數_python
- 2022-04-01 OpenCV實現摳圖工具_C 語言
- 2022-05-22 Python學習之os包使用教程詳解_python
- 2022-01-29 fastadmin自定義按鈕url,去掉默認的ids參數
- 2022-05-16 C++STL之vector模板類詳解_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支