Python:math.factorial是memoized吗?

Pad*_*118 6 python algorithm caching

我以三种不同的方式解决问题,其中两种是递归的,我自己也会记住它们.另一个不是递归的,而是使用math.factorial.我需要知道是否需要为其添加显式的memoization.

谢谢.

Sen*_*ran 5

Python 的 math.factorial 没有被记忆,它是一个简单的 for 循环,将值从 1 乘以你的 arg。如果您需要记忆,则需要明确地进行。

这是使用字典 setdefault 方法进行记忆的简单方法。

import math
cache = {}
def myfact(x):
    return cache.setdefault(x,math.factorial(x))
print myfact(10000)
print myfact(10000)
Run Code Online (Sandbox Code Playgroud)

  • 这不会带来任何性能优势。`setdefault` 与所有 Python 方法一样,始终评估其所有参数 - 当键已存在于字典中时它不会短路。相反,您需要使用“result = cache.get(x)”并测试 None 或“if x in cache: ...” 我自己也犯过同样的错误。`cache.get(x, math.factorial(x))` 也好不到哪儿去。 (8认同)

Ast*_*isk 4

在此链接上搜索 math_factorial,您将找到它在 python 中的实现:

http://svn.python.org/view/python/trunk/Modules/mathmodule.c?view=markup

PS这是针对python2.6的