Python - Count Maximum consecution of K in N consecutive batches

Python - Count Maximum consecution of K in N consecutive batches

In this tutorial, we'll determine the count of maximum consecutions of an element K in N consecutive batches from a list.

Objective:

Given a list lst, an element K, and a batch size N, break the list into batches of size N and determine the count of the most consecutive appearances of K in any of the batches.

For Example:

lst = [5, 5, 2, 5, 3, 5, 5, 5, 4, 5] K = 5 N = 3 

Here, the batches of size N=3 would be: [5,5,2], [5,3,5], [5,5,5], and [4,5].

The maximum consecutive appearance of K=5 is 3 in the third batch.

Step-by-step Solution:

1. Split the List into Batches:

First, we need to divide the list lst into batches of size N.

2. For Each Batch, Count Consecutive Appearances of K:

For each batch, iterate through the elements and keep a count of the most consecutive appearances of K.

3. Update the Maximum Count:

Keep track of the maximum consecutive count of K across all batches.

Complete Code:

def max_consecutive_K_in_batches(lst, K, N): # Split the list into batches of size N batches = [lst[i:i+N] for i in range(0, len(lst), N)] max_consecutive = 0 # Iterate over each batch for batch in batches: consecutive = 0 batch_max = 0 # Iterate over each element in the batch for elem in batch: if elem == K: consecutive += 1 batch_max = max(batch_max, consecutive) else: consecutive = 0 # Update the global maximum consecutive count max_consecutive = max(max_consecutive, batch_max) return max_consecutive # Sample list lst = [5, 5, 2, 5, 3, 5, 5, 5, 4, 5] K = 5 N = 3 # Test print(max_consecutive_K_in_batches(lst, K, N)) # Outputs: 3 

Additional Notes:

  • We use slicing to break the list into batches of size N.

  • The consecutive count for each batch is reset for each new batch. However, the maximum consecutive count (max_consecutive) is updated if a batch has more consecutive appearances of K than previously seen batches.

Through this tutorial, you've learned how to find the maximum consecutions of a given element K in N consecutive batches from a list. This approach can be useful in various data analysis tasks, especially when working with time-series data or sequences.


More Tags

background-color guava shadow-dom simulator robocopy logcat web3js sap-basis blazor-webassembly entity

More Programming Guides

Other Guides

More Programming Examples