Tommy Kay
Tommy Kay

Reputation: 103

Trying to get a diagonal sum

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))

Upvotes: 3

Views: 9176

Answers (3)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

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)))

Upvotes: 6

Rodrigo Ferreira
Rodrigo Ferreira

Reputation: 209

Use numpy.trace: http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.trace.html. It returns the sum along diagonals of the array.

import numpy as np

M = np.array([[2,3,1],[1,1,1],[5,6,4]])

print(M.trace())

#7

Upvotes: 2

halex
halex

Reputation: 16403

To get the diagonal elements you take the first in the first row, the second in the second row ... the nth in the nth row.

def diagonalsum(x):
    a = randomlists(x)
    return sum(row[i] for i, row in enumerate(a))

The not so concise alternative that uses a normal for loop reads

def diagonalsum(x):
    a = randomlists(x)
    result=0
    for i, row in enumerate(a):
        result += row[i]
    return result

Upvotes: 0

Related Questions