zltzlt 发表于 2020-3-28 08:11:07

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:}

zltzlt 发表于 2020-3-28 08:15:29

我的解法

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

永恒的蓝色梦想 发表于 2020-3-28 08:14:56

占楼

永恒的蓝色梦想 发表于 2020-3-28 08:16:18

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:18:03

本帖最后由 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:}

_2_ 发表于 2020-3-28 08:45:24

没有能力showtime

qiuyouzhi 发表于 2020-3-28 09:25:15

_2_ 发表于 2020-3-28 08:45
没有能力showtime

你写写试试呗
快乐就好

一个账号 发表于 2020-3-28 11:20:11

qiuyouzhi 发表于 2020-3-28 09:25
你写写试试呗
快乐就好

@_2_ 看不见你的回复

qiuyouzhi 发表于 2020-3-28 13:44:08

一个账号 发表于 2020-3-28 11:20
@_2_ 看不见你的回复

嗯,改了
页: [1]
查看完整版本: Python 重构 filter() 函数