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

推荐订阅源

H
Hackread – Cybersecurity News, Data Breaches, AI and More
宝玉的分享
宝玉的分享
月光博客
月光博客
爱范儿
爱范儿
阮一峰的网络日志
阮一峰的网络日志
酷 壳 – CoolShell
酷 壳 – CoolShell
Recent Announcements
Recent Announcements
A
About on SuperTechFans
T
The Blog of Author Tim Ferriss
博客园 - 叶小钗
U
Unit 42
aimingoo的专栏
aimingoo的专栏
Y
Y Combinator Blog
Martin Fowler
Martin Fowler
N
Netflix TechBlog - Medium
博客园 - 司徒正美
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
大猫的无限游戏
大猫的无限游戏
J
Java Code Geeks
V
Visual Studio Blog
腾讯CDC
IT之家
IT之家

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 語法 …