MDS0LDI3R
MDS0LDI3R

Reputation: 37

SageMath How to fix List for Taxicab numbers to be properly generated?

I am trying to write a function in SageMath that prints all Taxicab numbers (numbers who equal the sum of multiple sets of two values cubed and then added together) less than or equal to a certain value(in my code I refer this number as the variable t).

I can't seem to figure out how to make the appropriate changes for the lists(which I originally wrote in Python 2.7) to run in SageMath. As a result I keep getting the 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

Code:

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) should cause the function to print 2 values less than 10,000)

Do I need to declare the variables in my function as variable objects? Do I not need to create the blank list crev before populating it? Is it just a problem with how I am trying to use lists?

Upvotes: 0

Views: 83

Answers (1)

John Palmieri
John Palmieri

Reputation: 1696

I think the line crev[x3] = x + 1; should be crev.append(x+1): you can't assign the nth element in a list if the list has length less than n. Or you should create it using crev = [0]*t so that it initially contains all zeroes. Actually, though, if the function remains as written, that line should be deleted entirely: you never use crev in the remainder of the function.

Upvotes: 1

Related Questions