[英]How do I store results of a computation in Python so my program doesn't compute the same thing twice?
I keep having problems with programs in Python (I'm a complete newb) where it doesn't store the data from a computation and does it over and over again when I feel like it should have saved it.我在 Python(我是一个完全的新手)中的程序一直有问题,它不存储来自计算的数据,而是在我觉得它应该保存它时一遍又一遍地进行。 How can I make Python save the answer so it doesn't compute the program over and over?
我怎样才能让 Python 保存答案,这样它就不会一遍又一遍地计算程序?
ex:前任:
import prime
def g(x):
i=0
while i<len(prime.sieve(x)):
print str(prime.sieve(x)[i])+' is prime'
i=i+1
Here's the "prime" module in case someone wants to compile this:这是“主要”模块,以防有人想要编译它:
def sieve(max):
#Takes in a number, and returns all primes between 2 and that number
#Start with all of the numbers
primes = range(2,max+1)
#Start running through each number
for i in primes:
#Start with double the number, and
j = 2
#remove all multiples
while i * j <= primes[-1]:
#As long as the current multiple of the number
#is less than than the last element in the list
#If the multiple is in the list, take it out
if i * j in primes:
primes.remove(i*j)
j=j+1
return primes
Anyway, the first bit of code computes the list "prime.sieve(x)" over and over, and I want to save it for reference when printing.无论如何,第一段代码一遍又一遍地计算列表“prime.sieve(x)”,我想保存它以供打印时参考。
Thanks!谢谢!
rofls罗夫斯
saved_sieve_map = {}
def saved_sieve(x):
if x not in saved_sieve_map:
saved_sieve_map[x] = sieve(x)
return saved_sieve_map[x]
This is called memoization.这称为记忆。 Fortunately, there are lots of memoization decorators, and one of them is here: http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
幸运的是,有很多 memoization 装饰器,其中之一就在这里: http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
The example usage is:示例用法是:
@memoized
def fibonacci(n):
"Return the nth fibonacci number."
if n in (0, 1):
return n
return fibonacci(n-1) + fibonacci(n-2)
print fibonacci(12)
(The @memoized
expression applies the decorator to the function following it). (
@memoized
表达式将装饰器应用于它后面的 function)。
You might just assign it to a local variable:您可能只是将其分配给局部变量:
i=0
saveit = prime.sieve(x)
while i<len(saveit):
print str(saveit[i])+' is prime'
i=i+1
Note: it does still calculate the sieve even if g(x)
is called twice with the same value of x
.注意:即使使用相同的
x
值调用g(x)
两次,它仍会计算筛分。 For a version which does save the calculation even beyond the scope of g
see eg Keith's answer.对于保存计算甚至超出
g
的 scope 的版本,请参见 Keith 的回答。
This function can be used to remove recursive complexity.这个 function 可以用来去除递归的复杂性。
from functools import wraps
def memo(func):
cache = {}
@wraps(func)
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
Anyhow this is my implementation of the sieve which should run way faster than yours.无论如何,这是我对筛子的实现,它应该比你的运行速度更快。
@memo
def sieve(end):
import itertools
lng = ((end/2)-1+end%2)
sieve = [True]*(lng+1)
for i in itertools.ifilter(lambda z: sieve[z],xrange(int(end**0.5) >> 1)):
n=len(sieve[int((i*(i + 3) << 1) + 3): int(lng): int((i << 1) + 3)])
sieve[int((i*(i + 3) << 1) + 3): int(lng): int((i << 1) + 3)]=[False]*n
return sum([(x << 1) + 3 for x in itertools.compress(xrange(lng),sieve)])+2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.