今天看到了阶乘的直接算出来的办法:
fromfunctoolsimportreduce
classSolution:
"""
@param n: an integer
@return: the factorial of n
"""
deffactorial(self,n):
ifn ==orn ==1:
return'1'
result =str(reduce(lambdax,y: x*y,range(1,n+1)))
returnresult
使用reduce函数,对序列中的元素进行function操作,结果与序列中后面的元素继续进行function,累积至只剩下一个元素。
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
这个操作能直接返回阶乘结果...再将结果转化为字符串输出。
其实还没太理解这个,怎么就秒出结果了...
领取专属 10元无门槛券
私享最新 技术干货