所以我正在尝试制作一个主要筛子,它将使一个类对象将质数存储到用户给出的数字。但我希望在一个循环中运行,用户可以继续创建存储了素数列表的新对象,并为他们提供继续执行此操作的选项。
如果他们两次输入相同的数字,我想只打印以前的结果,这些结果存储在之前创建的对象中,而不是替换前一个对象并运行计算设置一个全新的列表。 / p>
如果你查看我的代码,筛子将正常工作,我只是不知道如何制作一个对象而不将其存储在变量'c'中
history={}
class Eratosthenes(object):
def __init__(self,b):
self.limitn=int(b)+1
self.not_prime = [False]*self.limitn
self.primes = []
def do_primes_sieve(self):
for i in range(2, self.limitn):
if self.not_prime[i]:
continue
for f in xrange(i**2, self.limitn, i):
self.not_prime[f] = True
self.primes.append(i)
def get_primes_til(self):
for i in self.primes:
print (i)
def get_num_of_primes(self):
print (len(self.primes))
a = True
while a:
b = raw_input("How far are you going to search?: ")
if b in history.keys():
c = history[b]
c.get_num_of_primes
else:
c = Eratosthenes(b)
history[b] = c
c.do_primes_sieve()
c.get_primes_til()
d = raw_input("Continue? (type 'yes' or 'no'): ")
if d == "yes":
continue
elif d == "no":
a=False
else:
print "This is a 'yes' or 'no' question. We're done here."
a=False
答案 0 :(得分:0)
你可以声明一些类变量(也就是静态变量),例如一个名为history
的字典,它将存储结果:
class Eratosthenes(object):
history = {}
def __init__(self,b):
self.limitn=int(b)+1
self.not_prime = [False]*self.limitn
self.primes = []
def do_primes_sieve(self):
if self.limitn-1 in Eratosthenes.history.keys():
self.primes = Eratosthenes.history[self.limitn-1]
else:
for i in range(2, self.limitn):
if self.not_prime[i]:
continue
for f in xrange(i**2, self.limitn, i):
self.not_prime[f] = True
self.primes.append(i)
Eratosthenes.history[self.limitn-1] = self.primes
然后,您可以修改do_primes_sieve
方法,这样,如果history
字典中存在先前的答案,则primes
的当前实例的Eratosthenes
将是从字典中取出。
根据下面的讨论,将history
视为全局的更新答案:
history = {}
class Eratosthenes(object):
def __init__(self,b):
self.limitn=int(b)+1
self.not_prime = [False]*self.limitn
self.primes = []
def do_primes_sieve(self):
for i in range(2, self.limitn):
if self.not_prime[i]:
continue
for f in range(i**2, self.limitn, i):
self.not_prime[f] = True
self.primes.append(i)
def get_primes_til(self):
for i in self.primes:
print i
def get_num_of_primes(self):
print len(self.primes)
a = True
while a:
b = raw_input("How far are you going to search?: ")
if b in history.keys():
c = history[b]
c.get_num_of_primes()
else:
c = Eratosthenes(b)
history[b] = c
c.do_primes_sieve()
c.get_primes_til()
d = raw_input("Continue? (type 'yes' or 'no'): ")
if d == "yes":
continue
elif d == "no":
a=False
else:
print "This is a 'yes' or 'no' question. We're done here."
a=False