網(wǎng)站首頁 編程語言 正文
python:實現(xiàn)利用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
相關(guān)推薦
- 2023-03-01 shell?創(chuàng)建子進程及并行延時執(zhí)行命令方法_linux shell
- 2022-05-26 ASP.NET?Core依賴注入詳解_實用技巧
- 2022-04-18 [webpack-cli] { Error: Cannot find module ‘a(chǎn)corn‘
- 2024-03-07 使用JdbcTemplate和Druid技術(shù)簡化持久層的編寫
- 2022-05-15 Python語言實現(xiàn)二分法查找_python
- 2022-10-17 Tomcat?Catalina為什么不new出來原理解析_Tomcat
- 2022-04-18 WPF框架Prism中對話框Dialog用法介紹_自學(xué)過程
- 2022-08-11 boost.asio框架系列之buffer函數(shù)_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支