Python – Count Maximum consecution of K in N consecutive batches
Last Updated :
22 Feb, 2023
Given a list, the task is to write a Python Program to count a maximum number of times K occurs consecutively in each batch of size N.
Example:
Input : test_list = [4, 4, 5, 4, 4, 4, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 5, 6, 7, 4, 4, 5, 3, 4, 4, 4, 7, 4, 4, 4, 5, 6, 3, 5, 4, 4, 4, 6, 4, 4, 1, 4, 2, 4, 4], N = 15, K = 4
Output : [6, 3, 3]
Explanation : For first batch of 15 elements, 4 occurs in consecution, 2, 3 and 6. times. Since 6 is maximum hence one of output.
Input : test_list = [4, 4, 5, 4, 4, 4, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 5, 6, 7, 4, 4, 5, 3, 4, 4, 4, 7, 4, 4, 4], N = 15, K = 4
Output : [6, 3]
Explanation : For first batch of 15 elements, 4 occurs in consecution, 2, 3 and 6. times. Since 6 is maximum hence one of output.
Method : Using groupby() + max() + list comprehension + slicing
In this, we get each consecution using slicing and using range to jump K elements to start grouping for each batch. The max() gets the maximum length of K consecutive group in each batch.
Python3
from itertools import groupby
test_list = [ 4 , 4 , 5 , 4 , 4 , 4 , 1 , 2 , 3 , 4 , 4 , 4 , 4 , 4 , 4 ,
4 , 5 , 6 , 7 , 4 , 4 , 5 , 3 , 4 , 4 , 4 , 7 , 4 , 4 , 4 ,
5 , 6 , 3 , 5 , 4 , 4 , 4 , 6 , 4 , 4 , 1 , 4 , 2 , 4 , 4 ]
print ( "The original list is : " + str (test_list))
N = 15
K = 4
res = [ max ( len ( list (group)) for ele, group in groupby(sub) if ele = = K)
for sub in (test_list[idx : idx + N]
for idx in range ( 0 , len (test_list), N))]
print ( "Maximum consecution of K for each batch : " + str (res))
|
Output:
The original list is : [4, 4, 5, 4, 4, 4, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 5, 6, 7, 4, 4, 5, 3, 4, 4, 4, 7, 4, 4, 4, 5, 6, 3, 5, 4, 4, 4, 6, 4, 4, 1, 4, 2, 4, 4]
Maximum consecution of K for each batch : [6, 3, 3]
Time Complexity: O(n*n)
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...