因子在Python中的功能

Nir*_*evy 121 python

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

sch*_*der 173

最简单的方法:math.factorial(x)(2.6及以上版本).

如果你想/必须自己写,请使用类似的东西

import math
math.factorial(1000)
Run Code Online (Sandbox Code Playgroud)

或更具可读性的东西:

def factorial(n):
    fact = 1
    for num in range(2, n + 1):
        fact *= num
    return fact
Run Code Online (Sandbox Code Playgroud)

一如既往,谷歌是你的朋友;)

  • @ J82:这里使用的概念称为递归(http://en.wikipedia.org/wiki/Recursion_(computer_science)) - 一个调用自身的函数非常精细并且通常很有用. (8认同)
  • 对于任何大于 998 的数字,递归函数都会引发 [`RecursionError`](https://docs.python.org/library/exceptions.html#RecursionError)(尝试 `factorial(999)`),除非你 [增加 Python 的递归限制](/sf/answers/232610591/) (5认同)
  • 我不明白你如何在`factorial`函数中使用`factorial`.如何在当前定义的函数中使用相同的函数?我是Python的新手,所以我只是想了解一下. (2认同)
  • 提高 CPython 的递归限制是危险的——你可能会杀死解释器。只是[不要在Python中使用递归](/sf/ask/4759217991/​​an-we-do-about-it)如果它可以得到帮助(通常可以,如本例所示)。 (2认同)

Jor*_*ril 113

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

import math
math.factorial(n)
Run Code Online (Sandbox Code Playgroud)


小智 24

没有必要,因为这是一个老线程.但我在这里做的是另一种使用while循环计算整数阶乘的方法.

def factorial(n):
    num = 1
    while n >= 1:
        num = num * n
        n = n - 1
    return num
Run Code Online (Sandbox Code Playgroud)

  • factorial(-1)将返回1,应该引发ValueError或其他东西. (4认同)

Tad*_*eck 18

现有解决方案

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

from math import factorial
print factorial(1000)
Run Code Online (Sandbox Code Playgroud)

建立自己的

您还可以构建自己的解决方案.一般来说,你有两种方法.最适合我的是:

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

print factorial(1000)
Run Code Online (Sandbox Code Playgroud)

(当结果变为时,它也适用于更大的数字long)

实现同样的第二种方式是:

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

print factorial(1000)
Run Code Online (Sandbox Code Playgroud)


小智 7

def factorial(n):
    if n < 2:
        return 1
    return n * factorial(n - 1)
Run Code Online (Sandbox Code Playgroud)

  • `factorial(999)` (及以上)将引发 `RuntimeError` 除非你[增加 Python 的递归限制](/sf/answers/232610591/) (3认同)

bin*_*bjz 7

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

def fact(n, total=1):
    while True:
        if n == 1:
            return total
        n, total = n - 1, total * n
Run Code Online (Sandbox Code Playgroud)

检查运行结果

cProfile.run('fact(126000)')
Run Code Online (Sandbox Code Playgroud)
def fact(n, total=1):
    while True:
        if n == 1:
            return total
        n, total = n - 1, total * n
Run Code Online (Sandbox Code Playgroud)

使用堆栈很方便(就像递归调用一样),但它是有代价的:存储详细信息可能会占用大量内存。

如果堆栈很高,则意味着计算机存储了大量有关函数调用的信息。

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

或者使用“for”循环

def fact(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result
Run Code Online (Sandbox Code Playgroud)

检查运行结果

cProfile.run('fact(126000)')
Run Code Online (Sandbox Code Playgroud)
cProfile.run('fact(126000)')
Run Code Online (Sandbox Code Playgroud)

或者使用内置函数 math

def fact(n):
    return math.factorial(n)
Run Code Online (Sandbox Code Playgroud)

检查运行结果

cProfile.run('fact(126000)')
Run Code Online (Sandbox Code Playgroud)
4 function calls in 5.164 seconds
Run Code Online (Sandbox Code Playgroud)


Jor*_*dan 5

def fact(n):
    f = 1
    for i in range(1, n + 1):
        f *= i
    return f
Run Code Online (Sandbox Code Playgroud)


Joh*_*ooy 5

如果您使用的是Python2.5或更早的尝试

from operator import mul
def factorial(n):
    return reduce(mul, range(1,n+1))
Run Code Online (Sandbox Code Playgroud)

对于较新的Python,数学模块中有因子,如此处的其他答案所示

  • 这是仅适用于 Python 2 的答案,“reduce”已从 Python 3 中删除。 (2认同)