Consecutive zeros
The goal of this challenge is to 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:
"1001101000110"
The biggest number of consecutive zeros is 3.
Define a function named consecutive_zeros
that takes a single parameter, which is the string of zeros and ones. Your function should return the number described above.
Â
==== SOLUTION ====
You can implement the `consecutive_zeros` function in Python by iterating through the binary string and keeping track of the maximum consecutive zeros encountered. Here’s how you can do it:
“`python
def consecutive_zeros(s):
        max_zeros = 0
        current_zeros = 0
        for char in s:
               if char == ‘0’:
                        current_zeros += 1
                        max_zeros = max(max_zeros, current_zeros)
               else:
                        current_zeros = 0
        return max_zeros
# Test the function
print(consecutive_zeros(“1001101000110”)) # Output: 3
“`
Explanation:
1. `def consecutive_zeros(s):`: This line defines a function named `consecutive_zeros` that takes a single parameter `s`, which is the binary string consisting of zeros and ones.
2. `max_zeros = 0`: This line initializes a variable `max_zeros` to keep track of the maximum number of consecutive zeros encountered.
3. `current_zeros = 0`: This line initializes a variable `current_zeros` to keep track of the number of consecutive zeros encountered in the current streak.
4. `for char in s:`: This loop iterates through each character in the binary string `s`.
5. `if char == ‘0’:`: This conditional statement checks if the current character is ‘0’.
6. `current_zeros += 1`: If the current character is ‘0’, it increments the `current_zeros` counter.
7. `max_zeros = max(max_zeros, current_zeros)`: This line updates the `max_zeros` counter to the maximum value between the current value of `max_zeros` and `current_zeros`. This ensures that `max_zeros` stores the maximum number of consecutive zeros encountered.
8. `else:`: If the current character is not ‘0’, it means the streak of consecutive zeros is broken, so we reset the `current_zeros` counter to 0.
9. Finally, the function returns `max_zeros`, which contains the maximum number of consecutive zeros encountered.
So, when you call `consecutive_zeros(“1001101000110”)`, it returns `3` because the biggest number of consecutive zeros in the string is 3.
Â