Open In App
Related Articles

Python – Test if K occurs N consecutive times

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Sometimes, while working with Python list, we can have a problem in which we need to check if a particular number occurs N consecutive times. This can have application in many domains including day-day programming. Let us discuss certain ways in which this task can be performed. 

Method #1: Using list comprehension

This is a way in which this task can be performed. In this, we iterate the list and check for occurrence in list using multiplication operator in a one liner. 

Python3

# Python3 code to demonstrate
# Test if K occurs N consecutive times
# using list comprehension
 
# Initializing list
test_list = [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing K
K = 4
 
# Initializing N
N = 3
 
# Test if K occurs N consecutive times
# using list comprehension
res = [K] * N in (test_list[i: i + N] for i in range(len(test_list) - N))
 
# printing result
print("Does K occur N consecutive times ? : " + str(res))

                    
Output : 
The original list is : [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
Does K occur N consecutive times ? : True

Time Complexity: O(n) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”. 

Method #2 : Using lambda + join()

This is yet another way to perform this task. In this, we perform the task of checking for consecution using lambda and join() is used to get the elements groups that are consecutive. 

Python3

# Python3 code to demonstrate
# Test if K occurs N consecutive times
# using lambda + join()
 
# Initializing list
test_list = [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing K
K = 4
 
# Initializing N
N = 3
 
# Test if K occurs N consecutive times
# using lambda + join()
res = bool(lambda ele: str(K) * N in ''.join(str(num) for num in test_list))
 
# printing result
print ("Does K occur N consecutive times ? : " + str(res))

                    
Output : 
The original list is : [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
Does K occur N consecutive times ? : True

The time complexity of this program is O(n), where n is the length of the input list. 

The auxiliary space complexity of this program is also O(n), because the program creates a new string that is the concatenation of all the elements of the input list.

Method #3: Using Sliding Window

This is a simple approach in which we use a sliding window of length N to find out the consecutive occurrence of K.

Python3

# Python3 code to demonstrate
# Test if K occurs N consecutive times
# using sliding window
   
# Initializing list
test_list = [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
   
# printing original list
print("The original list is : " + str(test_list))
   
# Initializing K
K = 4
   
# Initializing N
N = 3
   
# Test if K occurs N consecutive times
# using sliding window
def check_consecutive_occurrence(lst, k, n):
    for i in range(len(lst) - n + 1):
        if all(map(lambda x: x == k, lst[i : i + n])):
            return True
    return False
   
# storing result
res = check_consecutive_occurrence(test_list, K, N)
   
# printing result
print ("Does K occur N consecutive times ? : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy

                    

Output
The original list is : [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
Does K occur N consecutive times ? : True

Time Complexity: O(n) where n is the length of the list.
Auxiliary Space: O(1) as only a single loop variable is used.

Method#4: Using Recursive method.

Algorithm:

  1. Define a function check_consecutive that takes in test_list, K, N, and an optional parameter i.
  2. If i is greater than len(test_list) – N, return False as we can’t find the required sequence if we have less than N elements left in the list to search.
  3. Check if the sublist of test_list starting from index i and containing N elements is equal to a list of N elements of the value K. If so, return True as we have found the required sequence.
  4. If the sublist is not equal to the required sequence, call the check_consecutive function recursively with an incremented i as the starting index.
  5. If we have exhausted all the elements of the list without finding the required sequence, return False.

Python3

# Python3 code to demonstrate
# Test if K occurs N consecutive times
# using recursive function
 
def check_consecutive(test_list, K, N, i=0):
    if i > len(test_list) - N:
        return False
    if test_list[i:i+N] == [K] * N:
        return True
    return check_consecutive(test_list, K, N, i+1)
 
# Initializing list
test_list = [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing K
K = 4
  
# Initializing N
N = 3
 
res=check_consecutive(test_list, K, N)
# printing result
print ("Does K occur N consecutive times ? : " + str(res))
#this code contributed by tvsk

                    

Output
The original list is : [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
Does K occur N consecutive times ? : True

Time Complexity:
In the worst case, the function check_consecutive will need to iterate over the entire list test_list once. In addition, for each iteration, it will need to slice a sub-list of length N and compare it with a list of N elements of value K. The slicing operation and list comparison take constant time. Therefore, the time complexity of this algorithm is O(N * len(test_list)), which is proportional to the size of the input list and the length of the required consecutive sequence.

Auxiliary Space:
The space used by this algorithm is proportional to the number of recursive calls that the function makes. In the worst case, where the function reaches the end of the list without finding the required sequence, the number of recursive calls will be len(test_list) – N + 1. Therefore, the auxiliary space complexity of this algorithm is O(len(test_list)), which is proportional to the size of the input list.

Method#5: Using deque and count

  • Import the deque class from the collections module.
  • Using a deque object and creating a sliding window of length N. 
  • Checking if the window contains N consecutive occurrences of K. If yes, then True. If no, set it to False
  • Printing the result.

Python3

from collections import deque
 
# Initializing list
test_list = [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing K
K = 4
 
# Initializing N
N = 3
 
# Test if K occurs N consecutive times using deque and count
ans = deque([], N)
for i in test_list:
    ans.append(i)
    if ans.count(K) == N:
        res = True
        break
else:
    res = False
 
# printing result
print("Does K occur N consecutive times? : " + str(res))

                    

Output
The original list is : [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
Does K occur N consecutive times? : True

Time Complexity: O(N) as we iterate through the input list.

Auxiliary Space: O(N)  as we create a deque object of size N.

Method#6:Using reduce

Algorithm

1. Input the list of integers, K and N.
2. Define a lambda function that takes two arguments: acc and val.
3. Use reduce function to apply the lambda function to the list of integers.
4. If val is not equal to K, return a tuple with count reset to zero and the boolean value set to False.
5. If the count of consecutive occurrences of K reaches N-1, return a tuple with the count reset to zero and the boolean value set to True.
6. Otherwise, return a tuple with the count reset to zero and the boolean value unchanged.
7. Finally, return the boolean value indicating whether K occurs N consecutive times in the list or not.

Python3

# importing reduce from functools module
from functools import reduce
 
# Initializing list
test_list = [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing K
K = 4
 
# Initializing N
N = 3
 
# Test if K occurs N consecutive times
# using reduce function
res = reduce(lambda acc, val: (acc[0] + 1, False) if val != K else (0, True) if acc[0] == N-1 else (0, acc[1]), test_list, (0, False))[1]
 
# printing result
print("Does K occur N consecutive times? : " + str(res))
#This code is contributed by Vinay Pinjala.

                    

Output
The original list is : [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
Does K occur N consecutive times? : False

Time complexity:

The time complexity of the reduce() function is O(n), where n is the number of elements in the list. This is because the lambda function is applied to each element in the list exactly once.
Space complexity:

The space complexity of the reduce() function is O(1), as the lambda function uses a constant amount of memory to store the acc tuple.
The space complexity of the entire code is O(1), as we are only using a fixed amount of memory to store the list of integers, K, and N, and the intermediate tuples created by the lambda function are not stored in memory.

Method #7 : Using list(),map(),str, count() methods

Approach 

  1. Convert integer list to string list by using list(),map(),str and K to string using str()
  2. Now check whether count of string K in strings list is equal to N using count() method ,if True set result to True or else False

Python3

# Initializing list
test_list = [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing K
K = 4
 
# Initializing N
N = 3
 
# Test if K occurs N consecutive times
x=list(map(str,test_list))
res=x.count(str(K))==N
# printing result
print("Does K occur N consecutive times? : " + str(res))

                    

Output
The original list is : [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
Does K occur N consecutive times? : True

Time Complexity : O(N) N – length of given list

Auxiliary Space : O(1)

Method #8 : Using list(),map(),str, operator.countOf() methods

Approach

  1. Convert integer list to string list by using list(),map(),str and K to string using str()
  2. Now check whether count of string K in strings list is equal to N using operator.countOf() method ,if True set result to True or else False

Python3

# Initializing list
test_list = [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing K
K = 4
 
# Initializing N
N = 3
 
# Test if K occurs N consecutive times
import operator
x=list(map(str,test_list))
res=operator.countOf(x,str(K))==N
# printing result
print("Does K occur N consecutive times? : " + str(res))

                    

Output
The original list is : [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
Does K occur N consecutive times? : True

Time Complexity : O(N) N – length of given list

Auxiliary Space : O(1)


Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.


Last Updated : 08 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials