惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
罗磊的独立博客
M
MIT News - Artificial intelligence
G
Google Developers Blog
V
V2EX
D
Docker
博客园_首页
The Cloudflare Blog
人人都是产品经理
人人都是产品经理
Y
Y Combinator Blog
WordPress大学
WordPress大学
T
Tailwind CSS Blog
博客园 - 司徒正美
J
Java Code Geeks
L
LangChain Blog
博客园 - 三生石上(FineUI控件)
B
Blog RSS Feed
博客园 - 【当耐特】
小众软件
小众软件
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
P
Proofpoint News Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - Franky

ABB00717

HTB - SpeedNet PHP Filter to RCE Redis HTB - Pollution HTB - Pollution 工具 常見服務 HTB - BroScience HTB - BroScience 如何把爛爛的 shell 升級成好用的 TTY 滲透筆記 HTB - Imagery HTB - Imagery HTB - Reset HTB - Reset HTB - Trick HTB - Trick HTB - Editorial HTB - Editorial droopescan 安裝找不到 module imp 解決「桌面背景被當成一個視窗不斷重新彈出並覆蓋其他視窗」的問題 桌面不斷彈出覆蓋其他視窗 medusa 找不到 ssh module 中文文案排版指北 BugBounty Playbook 小知識 透過 Ubuntu 26 設定 Windows 11 雙系統並使用 Image Recovery 之踩坑全紀錄 透過 Ubuntu 26 設定 Windows 11 雙系統並使用 Image Recovery 之踩坑全紀錄 清除 git history 中的機敏資料 編譯器筆記
150. Evaluate Reverse Polish Notation
2026-08-12 · via ABB00717

https://leetcode.com/problems/evaluate-reverse-polish-notation/description/

其實題目蠻簡單的,大家應該都能寫出類似的邏輯:

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        operators = ['+', '-', '*', '/']
        stack = []
        for token in tokens:
            if token not in operators:
                stack.append(int(token))
            else:
                match token:
                    case '+':
                        s = stack.pop()
                        f = stack.pop()
                        stack.append(f + s)
                    case '-':
                        s = stack.pop()
                        f = stack.pop()
                        stack.append(f - s)
                    case '*':
                        s = stack.pop()
                        f = stack.pop()
                        stack.append(f * s)
                    case '/':
                        s = stack.pop()
                        f = stack.pop()
                        stack.append(int(f / s))
 
        return stack.pop()

但應該可以更善用 Python 的特性才對,請大哥幫我校對了一下:

  1. 可以改成 s, f = stack.pop(), stack.pop()
  2. 可以改成用字典加 lambda 來代替 match
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        operators = {
            '+': lambda a, b: int(a + b),
            '-': lambda a, b: int(a - b),
            '*': lambda a, b: int(a * b),
            '/': lambda a, b: int(a / b)
        }
        stack = []
        
        for token in tokens:
            if token not in operators:
                stack.append(int(token))
            else:
                s, f = stack.pop(), stack.pop()
                stack.append(operators[token](f, s))
 
        return stack.pop()

好耶,是說感覺對 lambda 超級不熟的,也覺得自己對程式的理解只停留在非常非常基礎的 C 語法 …