V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
MainHanzo
V2EX  ›  Python

Python yield 和 leetcode space optimization

  •  
  •   MainHanzo · 2020-04-18 18:15:58 +08:00 · 1754 次点击
    这是一个创建于 1470 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近刚好做到了 leetcode 844 这道题,说的是两个字符串,里面如果出现# 则代表用户回退上个输入字符,最后判断下两个输出字符是否相同。 我想到的最直接的解法是 On 时间 On 空间, 对每个 char 进行判断,然后遇到#就把最后一个删掉,最后比较。 看了下 solution 里的最优解是 O1 space 的,利用了 yield 这个关键词,在遍历字符串的时候每次只返回一个 char,然后进行判断,判断完就把这个 char 删掉。的确很巧妙,但是我提交了下发现使用空间和我的 On 没什么区别。

    我很好奇为什么会有这个现象,在 python3 里,yield 的优势已经不存在了吗?还是 leetcode 的空间计算有什么特性? 在写 leetcode 题时,该怎么正确降低 space 使用呢?

    5 条回复    2020-04-19 21:10:56 +08:00
    ipwx
        1
    ipwx  
       2020-04-18 18:28:12 +08:00
    所以答案连接?我看了一眼评论区,不少 O1 space 不用 yield 的呀,谁知道你 yield 怎么写的。
    ----

    减少 space 占用请用 C++。
    MainHanzo
        3
    MainHanzo  
    OP
       2020-04-19 20:52:55 +08:00
    @ipwx 不好意思 没看到咋传图。
    可是 Leetcode 里 space 的比较不应该是按语言分开的么。python 的 space performance 不可能直接和 c 语言做比价吧。
    MainHanzo
        4
    MainHanzo  
    OP
       2020-04-19 20:54:57 +08:00
    @ipwx https://leetcode.com/problems/backspace-string-compare/solution/ 是直接 solution 里的 python 解法, 用了 yiedl
    ipwx
        5
    ipwx  
       2020-04-19 21:10:56 +08:00
    itertools.izip_longest 是 python 2 的函数,python 3 叫做 itertools.zip_longest 。所以你说的这个版本的答案肯定是 python 2 。(这就尴尬了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   914 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 20:03 · PVG 04:03 · LAX 13:03 · JFK 16:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.