V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
laoyuan
V2EX  ›  Python

用 Python 写 Subsets 算法, lambda 里的 x 没有类型?

  •  
  •   laoyuan ·
    laoyuan · Jul 25, 2015 · 2501 views
    This topic created in 3929 days ago, the information mentioned may be changed or developed.
    class Solution:
        def subsets(self, S):
            if not S:
                return [[]]
            return map(lambda x: sorted([S[0]] + x), self.subsets(S[1:])) + self.subsets(S[1:])
            #return map(lambda x: sorted(x.append(S[0])), self.subsets(S[1:])) + self.subsets(S[1:])
    
    print Solution().subsets([1, 2])
    print Solution().subsets([3, 2, 1])
    

    注释里的写法报 TypeError: 'NoneType' object is not iterable,不让用append方法,但x 明明就是一个list 啊

    leavic
        1
    leavic  
       Jul 25, 2015
    骚年,你在哪里定义x是个list了,至少你这几行里我看不出来,实在不行你加个list()函数强制转成list不行吗
    laoyuan
        2
    laoyuan  
    OP
       Jul 25, 2015
    我错了,append 仅仅是修改对象,没有返回值。。。
    laoyuan
        3
    laoyuan  
    OP
       Jul 25, 2015
    顺便发一下reduce 版本:
    return reduce(lambda x, y: x + map(lambda z: sorted(z + [y]), x), [[[]]] + S)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1162 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 18:06 · PVG 02:06 · LAX 11:06 · JFK 14:06
    ♥ Do have faith in what you're doing.