Getting the Highest Sum of the columns and rows of a 4x4 matrix

Viewed 103

I currently have to figure out which row and which column has the highest sum of integers in my 4x4 matrix. The issue is that the matrix has to be randomly generated each time. Here is my code:

def nativeSolution():
    array = []
    for x in range(4):
        array.append([])
        for i in range(4):
            array[x].append(random.randint(0,1))
            print(array[x][i],end='')
        print()
    for row in array:
        rowArray = []
        rowArray[row].append(sum(row))
    print(rowArray)

My task as I said is to take the randomly output rows and find the one with the most 1s and then do the same with the columns. Thank you!

2 Answers

As I said in the comment, Numpy will be very helpful in this situation. If you dont want to use it, you have to reimplement every method I used here.

import numpy as np

arr = np.random.randint(0, 2, (4, 4))

print(arr)
print('Highest row (index={}, sum={}): {}'.format(
  arr.sum(axis=1).argmax(),
  arr.sum(axis=1).max(),
  arr[arr.sum(axis=1).argmax()])
)
print('Highest column (index={}, sum={}): {}'.format(
  arr.sum(axis=0).argmax(),
  arr.sum(axis=0).max(),
  arr[:, arr.sum(axis=0).argmax()])
)

# [[1 1 1 0]
#  [1 0 1 1]
#  [0 0 0 1]
#  [1 1 0 1]]
# Highest row (index=0, sum=3): [1 1 1 0]
# Highest column (index=0, sum=3): [1 1 0 1]

Pretty good chance you'll have at least 2 or more rows or columns with the same max number of 1s. You can use argwhere to filter the df by that number and get back all of the top rows/columns.

a = np.random.randint(2, size=(4,4))
print(a,'\n')
print(f'Max Col(s) {np.argwhere(a.sum(axis=0) == a.sum(axis=0).max()).flatten()}')
print(f'Max Row(s) {np.argwhere(a.sum(axis=1) == a.sum(axis=1).max()).flatten()}')

Output

[[0 0 1 1]
 [0 0 0 0]
 [0 1 1 1]
 [1 1 0 0]] 

Max Col(s) [1 2 3]
Max Row(s) [2]
Related