Home > OS >  You have a string that consist only of digits. You need to find how many zero digits ("0")
You have a string that consist only of digits. You need to find how many zero digits ("0")

Time:12-11

Our task is to count all the first zeros in the string of numbers, like '2333' should be counted as 0and '00980' be 2 .

I have several questions regarding this.

  1. So I came up with this solution:
def beginning_zeros(a: str) -> int:
    if map(lambda x: x!=0, a): 
        s=str(int(a))
        return len(a)-len(s)
   
    return len(a)

it works well for the non-all-zero string, but why it returns len(a)-1 when it comes to all '0' string?

like beginning_zeros('000') should be 3, but python count that as 2

and 2. about this solution:

def beginning_zero(a: str) -> int:

    a_num = int(a)
    if not a_num: # case a as all zeros

        return len(a)

    return len(a) - len(str(a_num))

it works perfectly, why is that not int(a) to execute the all-zero string? Is zero not counted int()? or is there more explanation?

CodePudding user response:

map(lambda x: x != 0, a) returns map-object that's always True, and it goes straight into if-block, so

it works well for the non-all-zero string, but why it returns len(a)-1 when it comes to all '0' string?

hehe, it's because str(int('000')) is still '0' and len('0') is 1.

CodePudding user response:

You just need a simple loop that examines the characters left to right as follows:

def leading_zeroes(s):
    r = 0
    for c in s:
        if c == '0':
            r  = 1
        else:
            break
    return r
  • Related