Our task is to print the element which occurs 3 consecutive times in a Python list.
Example :
Input : [4, 5, 5, 5, 3, 8] Output : 5 Input : [1, 1, 1, 64, 23, 64, 22, 22, 22] Output : 1, 22
Approach :
Example 1 : Only one occurrence of a 3 consecutively occurring element.
# creating the array arr = [4, 5, 5, 5, 3, 8] # size of the list size = len(arr) # looping till length - 2 for i in range(size - 2): # checking the conditions if arr[i] == arr[i + 1] and arr[i + 1] == arr[i + 2]: # printing the element as the # conditions are satisfied print(arr[i])
Output :
5
Example 2 : Multiple occurrences of 3 consecutively occurring elements.
# creating the array arr = [1, 1, 1, 64, 23, 64, 22, 22, 22] # size of the list size = len(arr) # looping till length - 2 for i in range(size - 2): # checking the conditions if arr[i] == arr[i + 1] and arr[i + 1] == arr[i + 2]: # printing the element as the # conditions are satisfied print(arr[i])
Output :
1 22