0

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

0

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your comments! It's working as expected, really appreciate the help :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.