Danish Xavier
Danish Xavier

Reputation: 1217

how to calculate the sum of elements other than the specified indices?

I have a 3*3 array of values

array([[20, 10, 30],
       [35, 45, 25],
       [15, 25, 35]])

I want to create a function where, when I pass a number argument it should sum all the rows and column elements smaller than the elements which fall on the number.

def sum_con (ar,a):

    y=a-1

    z=ar[0][0]+ar[0][1]+ar[1][0]+ar[1][1]

    return z


sum_con(array,2)
>>110

But you can see this code is not dynamic as it is not scaleable.

Can someone provide code for doing the same functionality for n shaped array.?

Upvotes: 1

Views: 133

Answers (1)

ZisIsNotZis
ZisIsNotZis

Reputation: 1740

For "other than", simply do the sum as usual and subtract/add accordingly:

def sum_con(a, n):
    return a.sum() - a[n].sum() - a[:,n].sum() + a[n,n]

This will make the n'th row and column "disappear" when summing.

For "smaller than", it's even easier:

def sum_con_2(a, n):
    return a[:n,:n].sum()

Upvotes: 4

Related Questions