[Tutor] Consecutive_zeros
Dennis Lee Bieber
wlfraed at ix.netcom.com
Sun Jul 3 20:37:25 EDT 2022
On Sun, 3 Jul 2022 14:05:57 -0700, Anirudh Tamsekar
<anirudh.tamsekar at gmail.com> declaimed the following:
>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.
>
This sounds very much like the core of run-length encoding
(https://en.wikipedia.org/wiki/Run-length_encoding), with a filter stage to
determine the longest run of 0s...
>def consecutive_zeros(string):
... which makes the name somewhat misleading. I'd generalize to something
like
longest_run(source, item)
where item is just one of the potential values within source data. That
would permit calls in the nature of:
longest_run(somedatasource, "0")
longest_run(somedatasource, "A")
longest_run(somedatasource, 3.141592654) #source is floats
> result = max(length)
You are only updating "result" when you encounter a non-"0" element. If
there is no non-"0" following any amount of "0" you will not update.
If not forbidden by the assignment/class, recommend you look at the
itertools module -- in particular groupby().
>>> import itertools as it
>>> source = "000100111010000122"
>>> for k, g in it.groupby(source):
... print("key %s: length %s:" % (k, len(list(g))))
...
key 0: length 3:
key 1: length 1:
key 0: length 2:
key 1: length 3:
key 0: length 1:
key 1: length 1:
key 0: length 4:
key 1: length 1:
key 2: length 2:
>>>
.takewhile() and .filterfalse() might also be of use.
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/
More information about the Tutor
mailing list