Python 重构 filter() 函数
本帖最后由 zltzlt 于 2020-3-29 12:53 编辑Python 重构 filter() 函数
要求
1. 完整实现 filter() 的功能
2. 代码中禁止使用 filter() BIF
格式
def filter(func, iterable):
# write your code here
或
class filter:
def __init__(self, func, iterable):
# your code
def __iter__(self):
return self
def __next__(self):
# your code
例子
>>> list(filter(None, ))
>>> list(filter(lambda x: x % 2 == 0, range(10)))
>>> for i in filter(lambda x: x != 5, ):
print(i)
4
6
7
3
NOW, IT'S YOUR SHOWTIME ! {:10_256:} 我的解法
class filter:
def __init__(self, func, iterable):
self.__f = bool if func is None else func
self.__i = iter(iterable)
def __iter__(self):
return self
def __next__(self):
while not self.__f(val := next(self.__i)):
pass
return val 占楼 def filter(function, iterable,/):
if function is None:
for i in iterable:
if i:
yield i
else:
for i in iterable:
if function(i):
yield i 本帖最后由 qiuyouzhi 于 2020-3-28 08:38 编辑
写完啦!不喜欢用类写函数
def filter(func, iterable):
if func is None:
for each in iterable:
if each:yield each
else:
for each in iterable:
if func(each):yield each
测试用例是都过了{:10_242:} 没有能力showtime _2_ 发表于 2020-3-28 08:45
没有能力showtime
你写写试试呗
快乐就好
qiuyouzhi 发表于 2020-3-28 09:25
你写写试试呗
快乐就好
@_2_ 看不见你的回复 一个账号 发表于 2020-3-28 11:20
@_2_ 看不见你的回复
嗯,改了
页:
[1]