我拥有一个名为的类Collatz
和一个创建该类对象的函数,我正在尝试使用collatz conjucturecollatz_it
生成一个数字达到 1 的步数,并使用生成器生成它们对应的步数,直到 100 万
import collatz
values = {}
count = 0
#collatz.collatz_it(n)
def gen():
n = 0
x = 0
while True:
yield x
n += 1
x = collatz.collatz_it(n)
for i in gen():
count += 1
values[count] = i
print values
if count == 1000000:
break
如您所见,我使用给定数字的 collatz 猜想生成了达到 1 所需的步数,并将其添加到具有相应数字的字典中,但是当我打印出字典值时,它的输出有点像这个:
{1: 0}
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>}
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>}
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>, 4: <collatz.Collatz instance at 0x01DCDFA8>}
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>, 4: <collatz.Collatz instance at 0x01DCDFA8>, 5: <collatz.Collatz instance at 0x01DCDEB8>}
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>, 4: <collatz.Collatz instance at 0x01DCDFA8>, 5: <collatz.Collatz instance at 0x01DCDEB8>, 6: <collatz.Collatz instance at 0x01DCDE90>}
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>, 4: <collatz.Collatz instance at 0x01DCDFA8>, 5: <collatz.Collatz instance at 0x01DCDEB8>, 6: <collatz.Collatz instance at 0x01DCDE90>, 7: <collatz.Collatz instance at 0x01DE8940>}
如果我打印print i
而不是print values
得到所需的输出,这基本上是因为该print
语句触发了__str__
类中的方法
有没有什么方法可以在不输入的情况下将实际步骤添加到字典<collatz.Collatz instance at 0x01DCDFA8>
中,是否有任何从方法中检索数据的__str__
方法,以便我的字典看起来像这样:
{1: 0}
{1: 0, 2: 1}
{1: 0, 2: 1, 3: 7}