What about counting zeros?
The basic instinct of most is to write a list comprehension:
max([len(i) for i in s.split('1')])It will work. But first you split the string (creating a list in memory), and then you loop over it to create another list of integers to feed to
max(). Double memory usage for no reason.But you can use a generator:
max((len(chunk) for chunk in s.split('1')))Memory-wise this is fine — no intermediate list of lengths is created. But speed-wise, generator expressions inside built-in functions in Python are slower due to the overhead of iteration and function calls at the bytecode level.
Even better:
max(map(len, s.split('1')))We get rid of the Python loop.
map is implemented in C, it's lazy, fast, and memory-efficient. Most people happily stop here.But... this is still not optimal. Ask yourself: why do we need to compute the lengths of all chunks before finding the maximum?
Strings in Python are compared lexicographically. Character by character. Therefore, the string
"000" is always greater than "00". We don't need to compute substring lengths for comparison at all.Do this instead!
len(max(s.split('1')))Why is this the best solution? 🤔
1. Calling
s.split('1') immediately returns a list of strings.2.
max() consumes this list and compares the strings themselves at the C level. No map, no len calls for each element, no function calls in a loop.3. We call
len() exactly once — on the winning string.Fewer interpreter operations = faster code.
#algosobes
Comments
0No comments yet.
Sign in to join the discussion.