Trying to get a diagonal sum

Tommy Kay picture Tommy Kay · Apr 12, 2013 · Viewed 8.6k times · Source

Trying to get the sum diagonally in #7 of the lists that #6 creates. So say the list was this [[2,3,1],[1,1,1],[5,6,4]] the sum would be 2+1+4

#6

def randomlists(s):
    b=s
    list1 = []
    while s>0:
        sublist = []
        for x in range(0,b):
            sublist.append(randrange(-100,101))
        list1.append(sublist)
        s-=1
    return list1
#print(randomlists(5))
#7

def diagonalsum(x):
    a=randomlists(x)
    count=0
    print (a)
    for b in a:
        while count<x:
            d=a[0]
            b=a[1]
            c=a[2]
            print (a[(count)])
            count+=1
        return d+b+c
print (diagonalsum(3))

Answer

&#211;scar L&#243;pez picture Óscar López · Apr 12, 2013

Assuming that the matrix is square, this is a standard solution using a loop:

def diagonalsum(m):
  count = 0
  for i in xrange(0, len(m)):
    count += m[i][i]
  return count

... Which can be written in a more concise way, by using generator expressions and the sum function:

def diagonalsum(m):
    return sum(m[i][i] for i in xrange(len(m)))