Counting elements inside an array/matrix

Question:

I am struggling with what is hopefully a simple problem. Haven’t been able to find a clear cut answer online.

The program given, asks for a user input (n) and then produces an n-sized square matrix. The matrix will only be made of 0s and 1s. I am attempting to count the arrays (I have called this x) that contain a number, or those that do not only contain only 0s.

Example output:

n = 3
[0, 0, 0] [1, 0, 0] [0, 1, 0]
In this case, x should = 2.

n = 4 
[0, 0, 0, 0] [1, 0, 0, 0] [0, 1, 0, 0] [0, 0, 0, 0]
In this case, x should also be 2.
def xArrayCount(MX):
  
    x = 0
    count = 0
    for i in MX:
      if i in MX[0 + count] == 0:
        x += 0
        count += 1
      else:
        x += 1
        count += 1
     return(x)

Trying to count the number of 0s/1s in each index of the matrix but I am going wrong somewhere, could someone explain how this should work?

(Use of extra python modules is disallowed)

Thank you

Asked By: newpythonstudent

||

Answers:

Those look like tuples, not arrays. I tried this myself and if I change the tuples into nested arrays (adding outer brackets and commas between the single arrays), this function works:

def xArrayCount(MX):
    x = 0
    count = 0

    for i in matrix:
        if MX[count][count] == 0:
            count += 1
        else:
            x += 1
            count += 1

    return x
Answered By: thicchead

You need to count all the lists that contain at least once the number one. To do that you can’t use any other module.

def count_none_zero_items(matrix):
    count = 0
    for row in matrix:
        if 1 in row:
            count += 1
    return count


x = [[0, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]]
count_none_zero_items(x)

Also notice that i changed the function name to lower case as this is the convention in python. Read more about it here:

Python3 Conventions

Also it’s worth mentioning that in python we call the variable list instead of array.

Answered By: Nimrod Shanny
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.