社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python中是否有一个函数可以将循环的所有迭代结果相乘?[重复]

definitelynotsam • 4 年前 • 2841 次点击  

如何在Python中计算整数的阶乘?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132193
文章 [ 10 ]  |  最新文章 4 年前
NickS1
Reply   •   1 楼
NickS1    4 年前

如果你喜欢的话,你也可以在一行中递归。这只是个人选择的问题。这里我们使用的是内联 if else 在Python中,类似于 ternary operator 在Java中:

Expression1 ? Expression2 : Expression3
  • 一行 function call 方法:

    def factorial(n): return 1 if n == 0 else n * factorial(n-1)
    
  • 一行 lambda 功能方法:

    (尽管不建议将lambda函数直接分配给名称,因为这被认为是一种不好的做法,可能会给代码带来不一致性。知道这一点总是好的。请参阅。) PEP8 .)

    factorial = lambda n: 1 if n == 0 else n * factorial(n-1)
    
Michael Hodel
Reply   •   2 楼
Michael Hodel    5 年前

非递归解决方案,无导入:

def factorial(x):
    return eval(' * '.join(map(str, range(1, x + 1))))
Sarah
Reply   •   3 楼
Sarah    7 年前

另一种方法是使用 np.prod 如下所示:

def factorial(n):
    if n == 0:
        return 1
    else:
         return np.prod(np.arange(1,n+1))
Boris V Jordan
Reply   •   4 楼
Boris V Jordan    7 年前
def fact(n):
    f = 1
    for i in range(1, n + 1):
        f *= i
    return f
Peter Mortensen John La Rooy
Reply   •   5 楼
Peter Mortensen John La Rooy    4 年前

如果您使用的是Python 2.5或更早版本,请尝试

from operator import mul

def factorial(n):
    return reduce(mul, range(1, n+1))

对于较新版本的Python,在 数学 其他答案中给出的模块。

Peter Mortensen John La Rooy
Reply   •   6 楼
Peter Mortensen John La Rooy    4 年前

出于性能原因,请不要使用递归。那将是灾难性的。

def fact(n, total=1):
    while True:
        if n == 1:
            return total
        n, total = n - 1, total * n

检查运行结果

cProfile.run('fact(126000)')

4 function calls in 5.164 seconds

使用堆栈很方便(就像递归调用),但它需要付出代价:存储详细信息可能会占用大量内存。

如果堆栈较高,则表示计算机存储了大量有关函数调用的信息。

该方法只占用常量内存(如迭代)。

或者使用“for”循环

def fact(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

检查运行结果

cProfile。运行(‘事实(126000)’)

4 function calls in 4.708 seconds

或者使用内置函数math

def fact(n):
    return math.factorial(n)

检查运行结果

cProfile。运行(‘事实(126000)’)

5 function calls in 0.272 seconds
Dennis Nishanth
Reply   •   7 楼
Dennis Nishanth    13 年前
def factorial(n):
    if n < 2:
        return 1
    return n * factorial(n - 1)
Tadeck
Reply   •   8 楼
Tadeck    13 年前

现有解决方案

最短、可能也是最快的解决方案是:

from math import factorial
print factorial(1000)

建立自己的

您还可以构建自己的解决方案。通常有两种方法。最适合我的是:

from itertools import imap
def factorial(x):
    return reduce(long.__mul__, imap(long, xrange(1, x + 1)))

print factorial(1000)

(当结果变为 long )

实现同样目标的第二种方法是:

def factorial(x):
    result = 1
    for i in xrange(2, x + 1):
        result *= i
    return result

print factorial(1000)
Arulx Z Joril
Reply   •   9 楼
Arulx Z Joril    11 年前

在Python 2.6及更高版本上,请尝试:

import math
math.factorial(n)
Peter Mortensen John La Rooy
Reply   •   10 楼
Peter Mortensen John La Rooy    4 年前

最简单的方法是使用 math.factorial (在Python 2.6及更高版本中提供):

import math
math.factorial(1000)

如果您想/必须自己编写,可以使用迭代方法:

def factorial(n):
    fact = 1
    for num in range(2, n + 1):
        fact *= num
    return fact

或者 recursive 方法:

def factorial(n):
    if n < 2:
        return 1
    else:
        return n * factorial(n-1)

请注意 factorial function 只为正整数定义,所以还应该检查 n >= 0 而且 isinstance(n, int) .如果不是,提出一个 ValueError 或者 TypeError 分别地 数学阶乘的 我会帮你处理的。