[Tutor] Consecutive_zeros

Mats Wichmann mats at wichmann.us
Sun Jul 3 18:10:46 EDT 2022


On 7/3/22 15:05, Anirudh Tamsekar wrote:
> Hello All,
> 
> Any help on this function below is highly appreciated.
> Goal: analyze a binary string consisting of only zeros and ones. Your code
> should find the biggest number of consecutive zeros in the string.
> 
> For example, given the string:
> Its failing on below test case
> 
> print(consecutive_zeros("0"))
> It should return 1. Returns 0
> 
> I get the max(length) as 1, if I print it separately
> 
> 
> def consecutive_zeros(string):
>     zeros = []
>     length = []
>     result = 0
>     for i in string:
>         if i == "0":
>             zeros.append(i)        else:
>             length.append(len(zeros))
>             zeros.clear()
>             result = max(length)
>     return result

you can certainly shorten that function, and even use a few tricks, but
that function looks like it would work for anything except the boundary
case you've given it.  Of course, boundary cases are one of the
challenges for programming - and writing good unit tests: "it works, but
what if you do something unexpected?"

Your problem is you only process the previous information if you see a
character that isn't zero, and since there's only a single zero in the
string it never triggers, so the saved count never gets collected.

Btw, there's no particular reason to use an array that you append zero
characters to and then take the length of, just use a counter.


More information about the Tutor mailing list