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
laoyuan
V2EX  ›  Python

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

  •  
  •   laoyuan ·
    laoyuan · 2015-07-25 07:08:30 +08:00 · 2107 次点击
    这是一个创建于 3199 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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  
       2015-07-25 14:04:09 +08:00
    骚年,你在哪里定义x是个list了,至少你这几行里我看不出来,实在不行你加个list()函数强制转成list不行吗
    laoyuan
        2
    laoyuan  
    OP
       2015-07-25 21:43:15 +08:00
    我错了,append 仅仅是修改对象,没有返回值。。。
    laoyuan
        3
    laoyuan  
    OP
       2015-07-25 21:43:58 +08:00
    顺便发一下reduce 版本:
    return reduce(lambda x, y: x + map(lambda z: sorted(z + [y]), x), [[[]]] + S)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   924 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 22:31 · PVG 06:31 · LAX 15:31 · JFK 18:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.