1281. Subtract the Product and Sum of Digits of an Integer
1281. Subtract the Product and Sum of Digits of an Integer
题目
Given an integer number n, return the difference between the product of its digits and the sum of its digits.
Example 1:
1 | Input: n = 234 |
Example 2:
1 | Input: n = 4421 |
Constraints:
1 <= n <= 10^5
解题
我的代码:
1 | class Solution(object): |
高赞代码:
1 | class Solution(object): |
总结
- reduce函数
1 | reduce(function, iterable[, initializer]) |
- function – 函数,有两个参数
- iterable – 可迭代对象
- initializer – 可选,初始参数
reduce函数与map函数不同,它们都将可迭代对象的每一个元素带入第一个函数中,但是前者将结果累计,后者则是分别对每个元素作用。
- python标准库中的operator模块
operator模块提供了一系列与Python自带操作一样有效的函数。
operator模块是用c实现的,所以执行速度比python代码快。
当使用 map、filter、reduce这一类高阶函数时,operator模块中的函数可以替换一些lambda。例如:
1 | reduce(lambda x,y:x*y, [1,2,3,4]) |
可以替换为:
1 | reduce(operator.mul, [1,2,3,4]) |