|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 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, [1, 2, 3, 4, 5, 6])
- 21
- >>> reduce(lambda x, y: x * 10 + y, [3, 6, 3, 8])
- 3638
- >>> reduce(lambda x, y: x * y, [1, 3, 5, 7])
- 105
- >>> reduce(lambda x, y: x * y, [1, 3, 5, 7], 10)
- 1050
复制代码
NOW, IT'S YOUR SHOWTIME !
- 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
复制代码
|
评分
-
查看全部评分
|