Error when determining the sum of entries with an even row and column index in a 2-D matrix

I’ve initialized an array function:

def create_array(k, n, d):
    return np.arange(k).reshape(n, d)

Summed even entries:

def calc_even_row_col_sum(arr):

    result = 0
    for i in arr:
        if not i % 2:
            result += i
    return result

Answer check:

stu_ans = calc_even_row_col_sum(create_array(k, n, d))
assert isinstance(stu_ans, np.number)

I receive the error:

“The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()”

Answer

In your code, when you use for i in arr, i represents a row of arr and not the index. Thus, doing if not i%2 is trying to apply the modulus operator to an entire row, prompting your error.

Try it like this instead:

def calc_even_row_col_sum(arr):
    result = 0
    for i, row in enumerate(arr):
        if i%2==0:
            result += row[::2].sum()
    return result

>>> calc_even_row_col_sum(np.arange(10).reshape(2, 5))
6

Alternative one-liner:

def calc_even_row_col_sum(arr):
    return arr[::2,::2].sum()