python计算n的阶乘的方法代码

yipeiwu_com5年前Python基础

整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,0的阶乘为1。即:n!=1×2×3×...×n。

首先导入math模块,然后调用factorial()函数来计算阶乘。

1 math.factorial(x)

import math

value = math.factorial(x)

2. reduce函数

def factorial(n):

return reduce(lambda x,y:x*y,[1]+range(1,n+1))

3. 递归实现

def factorial(n):  

  if n == 0:    

    return 1  

  else:    

    return n * factorial(n - 1)

以上就是python如何计算n的阶乘的详细内容,感谢大家的学习和对【听图阁-专注于Python设计】的支持。

相关文章

python操作gitlab API过程解析

这篇文章主要介绍了python操作gitlab API过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用 python-gi...

Python产生一个数值范围内的不重复的随机数的实现方法

Python产生一个数值范围内的不重复的随机数,可以使用random模块中的random.sample函数,其用法如下: import random random.sample(po...

Python I/O与进程的详细讲解

Python I/O与进程的详细讲解

I/O with语句 with context_expression [as target(s)]: with-body context_expression返回值遵从上下文...

python自定义类并使用的方法

本文实例讲述了python自定义类并使用的方法。分享给大家供大家参考。具体如下: class Person: def __init__(self, first, middle,...

Python中shapefile转换geojson的示例

shapefile转换geojson import shapefile import codecs from json import dumps # read the shapefi...