In Python I have tried to use the code below to fill a list with occurences of zeroes in rows of a matrix. These 0 must stand before all the non zero-numbers: for example in a row like [0,0,3,0] I would count only the first two zeroes.
occurence_of_zeroes=[0]*dim
for i in range(dim):
for j in range(dim):
while matrix[i][j]==0:
occurence_of_zeroes[i]=occurence_of_zeroes[i] 1
print("In row ",i 1," there are ",occurence_of_zeroes[i]," zeroes at the beginning")
print("Is this working?")
when I try to execute the code with previously defined dim
and matrix
, the console never spits out the result and freezes. Why?
CodePudding user response:
you can use NumPy arr it have build-in function
In [3]: arr
Out[3]:
array([[1, 2, 0, 3],
[3, 9, 0, 4]])
In [4]: np.count_nonzero(arr==0)
Out[4]: 2
In [5]:def func_cnt():
for arr in arrs:
zero_els = np.count_nonzero(arr==0)
# here, it counts the frequency of zeroes actually
CodePudding user response:
You are reaching an infinite loop in that while
because inside it you don't update any variable for it's condition
I assume what you want is something like below.
matrix = [
[0, 2, 3],
[0, 0, 3],
[0, 1, 0],
]
dim = 3 # 3 rows 3 columns I suppose
occurence_of_zeroes=[[] for _ in range(dim)]
for i in range(dim):
j = 0
while matrix[i][j]==0:
occurence_of_zeroes[i].append(j)
j =1
print(occurence_of_zeroes)
"""
[
[0],
[0, 1],
[0]
]
"""
CodePudding user response:
while matrix[i][j]==0:
occurence_of_zeroes[i]=occurence_of_zeroes[i] 1
is an infinite loop. Simply use if statement instead.
occurence_of_zeroes=[0]*dim
for i in range(dim):
for j in range(dim):
if matrix[i][j]==0:
occurence_of_zeroes[i]=occurence_of_zeroes[i] 1
print("In row ",i 1," there are ",occurence_of_zeroes[i]," zeroes at the beginning")
print("Is this working?")
CodePudding user response:
The problem is that you don't exit the while loop to increment j
. Here's a fix to your code.
occurence_of_zeroes=[0]*dim
for i in range(dim):
for j in range(dim):
if matrix[i][j]!=0:
break
occurence_of_zeroes[i]=occurence_of_zeroes[i] 1
print("In row ",i 1," there are ",occurence_of_zeroes[i]," zeroes at the beginning")
print("Is this working?")