首页
学习
活动
专区
工具
TVP
发布

阶乘

今天看到了阶乘的直接算出来的办法:

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.

这个操作能直接返回阶乘结果...再将结果转化为字符串输出。

其实还没太理解这个,怎么就秒出结果了...

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180401G0P7DB00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券