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
# Python3 code to demonstrate working of # Maximum consecution of K in N consecutive batches # Using groupby() + max() + list comprehension + slicing from itertools import groupby # initializing list 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 ] # printing original list print ( "The original list is : " + str (test_list)) # initializing N N = 15 # initializing K K = 4 # max() getting max. consecution of K, ranges being evaluated using slices # and skips using range() 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))] # printing result 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)