# Can't Figure out how to Fix IndexError Based on Len()

Can anyone help fix an error happening on the line "for i in range(1,len(sums)-1):"? I'm relevantly new to sage and more use to python but the few differences sage has I think have been taken into account but I can't figure out what is causing this IndexError..

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)


Error:

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


Does anyone have an idea of how to fix the IndexError I am running across?

edit retag close merge delete

Sort by ยป oldest newest most voted

You can not create an entry of a list if it is not already defined.

So, this is not possible:

sage: L = []
sage: L[0] = 5
IndexError: list assignment index out of range


However, you can modify an existing element of a list:

sage: L = [1,2,3]
sage: L[1] = 5
sage: L
[1, 5, 3]


You can also add an element to a list:

sage: L = [1,2,3]
sage: L.append(5)
sage: L
[1, 2, 3, 5]


In particular, the set of indices of a list must be an interval of the form {0,1,2,...,n-1}. In your case, the set of indicdes is not contiguous. So, you probably need a dictionary instead of a list:

sage: D = dict()
sage: D[123] = 1
sage: D[12] = 42
sage: D
{12: 42, 123: 1}
sage: D[123]
1

more