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

Building a function to count leading zeros in a string with no success

This is what I came up with:

def leading_zeros_counter(x: str):
    zeros = 0
    for i in x:
        if i == str(0):
            zeros += 1
        else:
            return int(zeros)

It seems to work on all strings, unless the string contains all zeros (e.g. ‘0000’ does not return ‘4’). Can anyone one explain why, and how to fix this?

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 :

You need to add a return statement out of the if condition:

def leading_zeros_counter(x: str):
    zeros = 0
    for i in x:
        if i == "0":
            zeros += 1
        else:
            return int(zeros)
    return int(zeros)
print(leading_zeros_counter("0000"))

So the output would be:

4
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