推荐学习书目
› 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
qdzzyb
V2EX  ›  Python

今天笔试遇到的一道题,请问还有其他做法吗?

  •  
  •   qdzzyb · Jan 20, 2016 · 6609 views
    This topic created in 3940 days ago, the information mentioned may be changed or developed.

    请实现函数 new_counter ,使得调用结果如下:

    c1 = new_counter(10)
    c2 = new_counter(20)
    print c1(), c2(), c1(), c2()
    
    outputs :
    11 21 12 22
    

    我的想法:

    def new_counter(n):
    
        class Counter(object):
            def __init__(self, num):
                self.num =num
    
            def __call__(self):
                self.num += 1
                return self.num
    
        return Counter(n)
    

    结束以后才想出来的,觉得比较麻烦,还有更简洁的方法吗?
    谢谢~

    Supplement 1  ·  Jan 20, 2016

    Python3

    def new_counter(num):
        count = num
        def counter():
            nonlocal count
            count += 1
            return count
        return counter
    

    Python2

    def new_counter(num):
        count = [num]
        def counter():
            count[0] += 1
            return count[0]
        return counter
    
    Supplement 2  ·  Jan 20, 2016
    看着像装饰器呢~
    30 replies  •  2016-01-22 18:18:58 +08:00
    jellyshen
    jellyshen
    Jan 20, 2016
    1
    ```python
    def new_count(n):
    print(n)
    def f():
    print(n+1)
    return f
    ```
    函数 f 里不能影响变量 n 的状态,还请大神们指教。
    deangl
    deangl
    Jan 20, 2016
    2
    def new_counter(init_val):
    _counter = [init_val, ]
    def add1():
    _counter[0] += 1
    return _counter[0]
    return add1
    zhangchioulin
    zhangchioulin
    Jan 20, 2016
    3
    LZ 是面试的什么?
    deangl
    deangl
    Jan 20, 2016
    4
    ```
    def new_counter(init_val):
    _counter = [init_val, ]
    def add1():
    _counter[0] += 1
    return _counter[0]
    return add1
    ```
    deangl
    deangl
    Jan 20, 2016
    5
    啊,求教怎么发贴带格式,怎么删自己的贴?
    jellyshen
    jellyshen
    Jan 20, 2016
    6
    问个问题,怎么在 V2EX 的回复里面排版代码?

    ```python
    def new_count(n):
    print(n)
    def f():
    print(n+1)
    return f
    ```
    zhangchioulin
    zhangchioulin
    Jan 20, 2016
    7
    @deangl 这个...哥你用的什么语言?为什么都 return 了还能执行?
    lxy42
    lxy42
    Jan 20, 2016
    8
    不会是搜狐吧
    lxy42
    lxy42
    Jan 20, 2016❤️1
    9
    用闭包就行了
    deangl
    deangl
    Jan 20, 2016❤️1
    10
    @zhangchioulin 我打不出缩进。。。。
    这个意思:

    def new_counter(init_val):
    ...._counter = [init_val, ]
    ....def add1():
    ........_counter[0] += 1
    ........return _counter[0]
    ....return add1
    tkpc
    tkpc
    Jan 20, 2016❤️5
    11
    new_counter = lambda n : (x+n for x in xrange(sys.maxint)).next
    fghzpqm
    fghzpqm
    Jan 20, 2016 via iPad
    12
    import itertools
    new_counter = itertools.count
    swirling
    swirling
    Jan 20, 2016 via iPhone
    13
    high order function ,这时候你就和面试官聊聊函数式什么就好了。
    dapang1221
    dapang1221
    Jan 20, 2016
    14
    python 生成器?用 yield 传出来就好了,不要用 return ……但是调用起来又得用 next 了。。。
    def counter(n):
    ....while True:
    ........n=(yield n+1)
    snailsir
    snailsir
    Jan 20, 2016 via iPhone❤️1
    15
    闭包
    mengzhuo
    mengzhuo
    Jan 20, 2016❤️1
    16
    我来上个优雅点的吧:
    def new_counter(i):
    ....def c():
    ........c.var += 1
    ........return c.var
    ....c.var = i
    ....return c


    c10 = new_counter(10)
    c20 = new_counter(20)

    print c10(), c20(), c10(), c20() #11, 21, 12, 22
    airqj
    airqj
    Jan 20, 2016 via Android
    17
    记不清实现了
    应该是闭包
    ChiangDi
    ChiangDi
    Jan 21, 2016 via Android
    18
    这个是最简单的闭包应用啊, Python 不熟,随便用 js 码个
    function new_count(n) {
    return function() {
    n ++
    console.log(n)
    }

    还有比这个更简单的实现吗?
    elvba
    elvba
    Jan 21, 2016
    19
    function new_counter($t) { return function () use (&$t) { return $t += 1; }; }
    SpicyCat
    SpicyCat
    Jan 21, 2016❤️1
    20
    @ChiangDi @airqj @dapang1221 @deangl @elvba @fghzpqm @jellyshen @lxy42 @mengzhuo @qdzzyb 楼上所有,友情提示,贴代码可以用 github 的 gist ,参考此贴: https://www.v2ex.com/t/130567
    master13
    master13
    Jan 21, 2016❤️1
    21
    感觉做一个生成器,或者 yield 把……
    cppgohan
    cppgohan
    Jan 21, 2016
    22
    用 itertools 偷懒可以吗?

    ```
    def new_counter(c):
    counter = itertools.count(c)
    def f():
    return counter.next()
    return f;
    ```

    ```
    class new_counter(itertools.count):
    def __init__(self, *args, **kwargs):
    super(new_counter, self).__init__(*args, **kwargs)
    def __call__(self):
    return self.next()
    ```
    ttycode
    ttycode
    Jan 21, 2016 via Android
    24
    闭包,或者匿名函数
    motopig
    motopig
    Jan 21, 2016
    25
    ``` php
    function counter($num)
    {
    return function () use (&$num) {
    return ++$num."<br>";
    };
    }
    $c1 = counter(10);
    $c2 = counter(20);
    echo $c1();
    echo $c2();
    echo $c1();
    echo $c2();

    ```
    youkochan
    youkochan
    Jan 21, 2016❤️1
    26
    def new_counter(_num):
    def foo():
    num = _num
    while True:
    num += 1
    yield num
    a = foo()
    return a.next

    c1 = new_counter(10)
    c2 = new_counter(20)

    print c1(), c2(), c1(), c2()
    shajiquan
    shajiquan
    Jan 21, 2016❤️1
    27
    我觉得楼主提出的 class 方式就挺好的,清晰直观,不用理会变量的作用域带来的困扰。#16 楼的方法挺好玩的。
    qiu0130
    qiu0130
    Jan 21, 2016
    28
    C pa pa 重载()运算符.
    necomancer
    necomancer
    Jan 22, 2016❤️2
    29
    ```python3
    def new_counter(m):
    ....def counter(m):
    ........while 1:
    ............m +=1
    ............yield m
    ....return counter(m).__next__

    c1 = new_counter(10)
    c2 = new_counter(20)
    print(c1(), c2(), c1(), c2())
    ```
    没 16 楼的简洁……
    necomancer
    necomancer
    Jan 22, 2016
    30
    啊……原来 26 楼已经是这个办法了……
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4912 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 66ms · UTC 08:04 · PVG 16:04 · LAX 00:04 · JFK 03:04
    ♥ Do have faith in what you're doing.