In a 2D Numpy Array find max streak of consecutive 1's

You can find the maximum streak of consecutive 1's in a 2D Numpy array by using a nested loop to iterate over each row and column, and keeping track of the length of the current streak of 1's. The maximum length of any streak found can then be stored and updated as the loop continues.


Here's an example implementation in Python:


python

Copy code

import numpy as np


def find_max_streak(arr):

    max_streak = 0

    for row in arr:

        streak = 0

        for val in row:

            if val == 1:

                streak += 1

            else:

                max_streak = max(max_streak, streak)

                streak = 0

        max_streak = max(max_streak, streak)

    return max_streak


# Example 2D Numpy array

arr = np.array([[1, 0, 1, 1, 0, 1],

                [0, 1, 1, 1, 1, 0],

                [1, 0, 1, 1, 0, 1]])


# Find the maximum streak of consecutive 1's

max_streak = find_max_streak(arr)

print("Max streak:", max_streak)

In this example, the function find_max_streak takes a 2D Numpy array as input, and returns the length of the longest streak of consecutive 1's found in the array. The function uses two nested loops to iterate over each row and column of the array, and a variable streak to keep track of the current streak of 1's. The maximum value of streak is updated and stored in max_streak whenever a 0 is encountered or when the loop reaches the end of a row. After the loops have completed, the final value of max_streak will be the length of the longest streak of consecutive 1's found in the array.


In this example, the output will be:


yaml

Copy code

Max streak: 4

This indicates that the longest streak of consecutive 1's in the 2D Numpy array is 4.


It's worth noting that this implementation assumes that the input array only contains 0's and 1's. If the input array contains other values, the implementation will need to be modified to handle them appropriately.


This is a simple and straightforward approach to finding the maximum streak of consecutive 1's in a 2D Numpy array. By using Numpy's built-in array manipulation capabilities, you can easily write efficient and readable code that can be used to solve a variety of data processing problems.

Post a Comment

Previous Post Next Post