【发布时间】:2017-07-23 03:53:13
【问题描述】:
所以我正在尝试制作一个质数筛,它将生成一个类对象,该对象将质数存储到用户给出的数字。但我想在一个循环中运行,用户可以继续创建存储有素数列表的新对象,并让他们可以选择继续这样做。
如果他们两次输入相同的数字,我只想打印之前创建的对象中存储的先前结果,而不是替换先前的对象并运行建立一个全新列表的计算。
- 我认为唯一让我感到困惑的是如何不断地创建新的类对象并每次都给对象新的名称,而不是我第一次做的,将对象存储在变量中'C'。
如果你看我的代码,筛子会正常工作,我只是不知道如何制作一个对象而不将它存储在变量'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
【问题讨论】:
-
一个类对象?
-
是一个类对象
-
你关心 old 实例吗?你所拥有的有什么问题?
-
我的目标是创建一个新实例,这样我就可以在适当的位置创建实例,用户只需再次输入他们的号码就可以调用它们。
-
将实例作为键/值对添加到字典中 -
number:instance。
标签: python class object sieve-of-eratosthenes