zltzlt 发表于 2020-3-31 21:35:27

Python 重构 reduce() 函数

本帖最后由 zltzlt 于 2020-4-1 22:13 编辑

Python 重构 reduce() 函数

要求

      1. 完整实现 functools.reduce() 的功能
      2. 代码中禁止使用 functools.reduce()

格式

def reduce(func, iterable, initial=None):
    # write your code here

例子

>>> reduce(lambda x, y: x + y, )
21
>>> reduce(lambda x, y: x * 10 + y, )
3638
>>> reduce(lambda x, y: x * y, )
105
>>> reduce(lambda x, y: x * y, , 10)
1050

NOW, IT'S YOUR SHOWTIME ! {:10_256:}

永恒的蓝色梦想 发表于 2020-3-31 21:36:02

reduce为什么代码中禁止使用 filter() BIF?

永恒的蓝色梦想 发表于 2020-3-31 21:37:16

def reduce(function, sequence, initial=NotImplemented):
    iterator=iter(sequence)

    if initial is NotImplemented:
      try:
            initial=next(iterator)

      except StopIteration:
            raise TypeError("reduce() of empty sequence with no initial value")
   
    for i in initial:
      initial=function(initial,i)

    return initial

永恒的蓝色梦想 发表于 2020-4-1 22:15:24

就我一个回答了啊……

zltzlt 发表于 2020-4-1 22:16:20

永恒的蓝色梦想 发表于 2020-4-1 22:15
就我一个回答了啊……

{:10_277:}

永恒的蓝色梦想 发表于 2020-4-1 22:17:39

zltzlt 发表于 2020-4-1 22:16


好可怜,捞一捞{:10_262:}

_2_ 发表于 2020-5-12 10:13:49

I THINK I AM NOT SURE. I CANNOT RECONSTRUCT THE FUNCTION reduce().
{:10_266:}

一个账号 发表于 2021-1-5 22:23:33

都没继续更新了。。。{:10_277:}
页: [1]
查看完整版本: Python 重构 reduce() 函数