[Tutor] Consecutive_zeros

Peter Otten __peter__ at web.de
Mon Jul 4 03:51:01 EDT 2022


On 03/07/2022 23: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

In case you haven't already fixed your function here's a hint that is a
bit more practical than what already has been said.

>
> 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)

At this point in the execution of your function what does zeros look
like for the succeeding cases, and what does it look like for the
failing ones? Add a print(...) call if you aren't sure and run
consecutive_zeros() for examples with trailing ones, trailing runs of
zeros that have or don't have the maximum length for that string.

How can you bring result up-to-date?

>      return result

PS: Because homework problems are often simpler than what comes up in
the "real world" some programmers tend to come up with solutions that
are less robust or general. In that spirit I can't help but suggest

 >>> max(map(len, "011110000110001000001111100".split("1")))
5

which may also be written as

 >>> max(len(s) for s in "011110000110001000001111100".split("1"))
5

Can you figure out how this works?
What will happen if there is a character other than "1" or "0"in the string?


More information about the Tutor mailing list