[Tutor] Consecutive_zeros
Peter Otten
__peter__ at web.de
Tue Jul 5 03:55:11 EDT 2022
On 04/07/2022 18:49, avi.e.gross at gmail.com wrote:
> So I went back to my previous somewhat joking suggestion and thought of a
> way of shortening it as the "re" module also has a regular-expression
> version called re.split() that has the nice side effect of including an
> empty string when I ask it to split on all runs of non-zero.
>
> re.split("[^0]", "1010010001000010000001")
> ['', '0', '00', '000', '0000', '000000', '']
>
> That '' at the end of the resulting list takes care of the edge condition
> for a string with no zeroes at all:
>
> re.split("[^0]", "No zeroes")
> ['', '', '', '', '', '', '', '', '', '']
>
> Yes, lots of empty string but when you hand something like that to get
> lengths, you get at least one zero which handles always getting a number,
> unlike my earlier offering which needed to check if it matched anything.
>
> So here is a tad shorter and perhaps more direct version of the requested
> function which is in effect a one-liner:
>
> def consecutive_zeros(string):
> return(max([len(zs) for zs in re.split("[^0]", string)]))
Python's developers like to tinker as much as its users -- but they
disguise it as adding syntactic sugar or useful features ;)
One of these features is a default value for max() which allows you to
stick with re.findall() while following the cult of the one-liner:
>>> max(map(len, re.findall("0+", "1010010001000010000001")), default=-1)
6
>>> max(map(len, re.findall("0+", "ham spam")), default=-1)
-1
More information about the Tutor
mailing list