SageMath如何修复要正确生成的出租车编号列表?

时间:2015-10-12 15:25:38

标签: sage

我正在尝试在SageMath中编写一个函数,它打印所有的Taxicab数字(数字等于两个值的总和,然后加在一起的多个值的总和)小于或等于某个值(在我的代码中我引用这个数字作为变量t)。

我似乎无法弄清楚如何对列表(我最初在Python 2.7中编写)进行适当的更改以在SageMath中运行。结果我不断收到错误:

Traceback (most recent call last):            for i in range(1,len(sums)-1):
  File "", line 1, in <module>

File "/private/var/folders/96/g5hyl4ps29dglpy8fnwww6x80000gn/T/tmpWiTKG1/___code___.py", line 16, in <module>
exec compile(u'Ramanujan(_sage_const_10000 )
File "", line 1, in <module>

File "/private/var/folders/96/g5hyl4ps29dglpy8fnwww6x80000gn/T/tmpWiTKG1/___code___.py", line 7, in     Ramanujan
crev[x3] = x + _sage_const_1 ;
IndexError: list assignment index out of range

代码:

def Ramanujan(t):
    cubes = [x**3 for x in range(1,t/10)];
    crev = [] # Calculating Cube Roots;
    for x,x3 in enumerate(cubes):
        crev[x3] = x + 1;
        sums = sorted(x + y for x in cubes for y in cubes if y < x) # Organizing Data
        for i in range(1,len(sums)-1):
            if sums[i-1] != sums[i] and sums[i] == sums[i+1]: # Finding solutions
                if sums[i]<=t: # Limiting how many solutions printed.
                    print "%10d"%(sums[i]) # Printing desired outputs
                else:
                    break # Ending the function.

Ramanujan(10000)

(Ramanujan(10000)应该使该函数打印2个小于10,000的值)

我是否需要将函数中的变量声明为变量对象? 在填充之前我是否不需要创建空白列表crev? 这只是我试图使用列表的问题吗?

1 个答案:

答案 0 :(得分:1)

我认为行crev[x3] = x + 1;应该是crev.append(x+1):如果列表的长度小于n,则无法在列表中分配n元素。或者您应该使用crev = [0]*t创建它,以便它最初包含全零。实际上,如果函数仍然是写的,那么该行应该完全删除:你永远不会在函数的其余部分使用crev

相关问题