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
CodePudding user response:
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
CodePudding user response:
If i understood you correctly, 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(my_list):
count = 0
for lst in my_list:
if 1 in lst:
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:
Also it's worth mentioning that in python we call the variable list instead of array :)
Good luck !