Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problems counting zeroes standing at the beginning of rows in a matrix

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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?")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading