Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

I was hesitating somehow to post this answer, but the decision to post an answer comes from the fact that we had a quarter of beginning code, but which is not the way i would do the job.


First let us improve the given start to have a solution:

A = matrix( ZZ, [ [4, 1, 6], [1, 3, 9], [2, 7, 25] ] )

def sum_quadrate(A):
    m = A.nrows()
    n = A.ncols()
    result = 0
    for j in range (m):
        for k in range(n): 
            entry = A[j, k]
            if entry.is_square():
                result += entry
    return result

print sum_quadrate(A)

The above gives the 40 as a result. And now the many comments. Please always use four spaces to indent. This is a good style, and saves a lot of troubles. In fact, we need only an access to the entries of $A$, so we need a "better way to loop". The suggestions of tmonteil already give the answer, so a better way to do the job...


... is the following way:

A = matrix( ZZ, [ [4, 1, 6], [1, 3, 9], [2, 7, 25] ] )

def sum_quadrate(A):
    result = 0
    for entry in A.list():
        if entry.is_square():
            result += entry
    return result

print sum_quadrate(A)

Again we get that 40. This is again not the best way to do the job. Instead...


... using list comprehension we can get some mathematically easily readable version of the function:

def sum_quadrate(A):
    return sum([0]+[entry for entry in A.list() if entry.is_square()])

Note: The [0]+ part is needed for the case there is no perfect square in the list of entries of $A$.