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. How can I make Python save the answer so it doesn’t compute the program over and over?
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.
Thanks!
rofls
1 Answer