gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:04:02 25 4
gpt4 key购买 nike

我一直在使用 Python 程序时遇到问题(我是一个完全的新手),它不存储来自计算的数据,而是在我觉得它应该保存它时一遍又一遍地进行。我怎样才能让 Python 保存答案,这样它就不会一遍又一遍地计算程序?

例如:

import prime
def g(x):
i=0
while i<len(prime.sieve(x)):
print str(prime.sieve(x)[i])+' is prime'
i=i+1

这里是“主要”模块,以防有人想编译它:

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

无论如何,第一段代码一遍又一遍地计算列表“prime.sieve(x)”,我想保存它以供打印时引用。

谢谢!

罗夫斯

最佳答案

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]

关于python - 如何在 Python 中存储计算结果,这样我的程序就不会对同一事物进行两次计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10052698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com