Ask Your Question

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

asked 2015-10-12 00:06:50 -0500

KristofferH gravatar image

updated 2015-10-12 00:52:21 -0500

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
                    break # Ending the function.



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/", line 16, in <module>
exec compile(u'Ramanujan(_sage_const_10000 )
File "", line 1, in <module>

File "/private/var/folders/96/g5hyl4ps29dglpy8fnwww6x80000gn/T/tmpWiTKG1/", 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 flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2015-10-12 01:04:44 -0500

tmonteil gravatar image

updated 2015-10-12 01:08:28 -0500

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]
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2015-10-12 00:06:50 -0500

Seen: 139 times

Last updated: Oct 12 '15