简体   繁体   English

如何将计算结果存储在 Python 中,这样我的程序就不会对同一事物进行两次计算?

[英]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.

相关问题 我的用于计算用户输入语句中的元音数量的程序不会对同一元音进行两次计数。 我该如何解决? - My program for counting how many vowels in a user input sentence doesn't count the same vowel twice. How do i fix this? 如何存储 python 程序的结果,以便下次不必重新运行所有代码? - How can I store the results of python program so I don't have to re-run all the code next time? 如何关闭“ while”循环,以使程序不会无限循环? - How do I close out my 'while' loop so the program doesn't loop infinitely? 确保测验不会两次问同样的问题 - Making sure a quiz doesn't ask the same thing twice 为什么del不做同样的事情? - Why doesn't del do the same thing? 如何有效地从大型excel文件中读取数据,进行计算,然后将结果存储回python中? - How to efficiently read data from a large excel file, do the computation and then store results back in python? 为什么我需要点击两次才能退出我的 python 程序? - Why do I need to click twice to exit my python program? 阻止程序两次询问同一件事? - Stop the program from asking the same thing twice? 我如何继续循环我的程序,以便用户可以输入尽可能多的内容? - How do i keep looping the same my program so the user can input as much as they want? 为什么 `while i==50` 不做与 `while i&lt;=50` 相同的事情? - Why doesn't `while i==50` do the same thing as `while i<=50`?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM