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

2016-01-20 20:53:56 +08:00
 qdzzyb

请实现函数 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)

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

4994 次点击
所在节点    Python
30 条回复
master13
2016-01-21 11:22:57 +08:00
感觉做一个生成器,或者 yield 把……
cppgohan
2016-01-21 12:04:35 +08:00
用 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()
```
cppgohan
2016-01-21 12:07:18 +08:00
ttycode
2016-01-21 12:45:21 +08:00
闭包,或者匿名函数
motopig
2016-01-21 13:29:08 +08:00
``` 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
2016-01-21 15:38:29 +08:00
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
2016-01-21 17:04:26 +08:00
我觉得楼主提出的 class 方式就挺好的,清晰直观,不用理会变量的作用域带来的困扰。#16 楼的方法挺好玩的。
qiu0130
2016-01-21 22:00:03 +08:00
C pa pa 重载()运算符.
necomancer
2016-01-22 18:14:41 +08:00
```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
2016-01-22 18:18:58 +08:00
啊……原来 26 楼已经是这个办法了……

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/252207

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX