Python – Alternate elements Similarity
Given list of elements, check if all the alternate elements are equal to K.
Input : test_list = [5, 3, 5, 2, 5, 8, 9], K = 5 Output : False Explanation : 9 != 5, hence False. Input : test_list = [4, 3, 4, 2, 4], K = 4 Output : True Explanation : All alternates equal to 4.
Method #1 : Using loop
This is brute way to solution to this problem. In this, iterate for each element in list and check for each element if they are equal to K.
Python3
test_list = [ 5 , 3 , 5 , 2 , 5 , 8 , 5 ]
print ( "The original list : " + str (test_list))
K = 5
res = True
for idx, ele in enumerate (test_list):
if not idx % 2 and ele ! = K:
res = False
break
print ( "Are all alternate elements equal to K : " + str (res))
|
Output
The original list : [5, 3, 5, 2, 5, 8, 5]
Are all alternate elements equal to K : True
Time Complexity: O(n), where n is the size of list
Auxiliary Space: O(n), where n is the size of list
Method #2 : Using all() + generator expression
This is yet another way in which this task can be performed. In this, we check for all elements using all() and generator expression is used for condition check and iteration.
Python3
test_list = [ 5 , 3 , 5 , 2 , 5 , 8 , 5 ]
print ( "The original list : " + str (test_list))
K = 5
res = all (test_list[idx] = = K for idx in range ( 0 , len (test_list), 2 ))
print ( "Are all alternate elements equal to K : " + str (res))
|
Output
The original list : [5, 3, 5, 2, 5, 8, 5]
Are all alternate elements equal to K : 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 3 : using list slicing.
steps for this approach:
Initialize the list and the value of K.
Get a sublist of alternate elements by slicing the list with a step of 2.
Check if all elements in the sublist are equal to K using the all() function.
Print the result.
Python3
test_list = [ 5 , 3 , 5 , 2 , 5 , 8 , 5 ]
print ( "The original list : " + str (test_list))
K = 5
sub_list = test_list[:: 2 ]
res = all (elem = = K for elem in sub_list)
print ( "Are all alternate elements equal to K : " + str (res))
|
Output
The original list : [5, 3, 5, 2, 5, 8, 5]
Are all alternate elements equal to K : True
Time complexity of this code is O(n/2), as we are slicing the list with a step of 2, and iterating over only half of the original list.
Auxiliary space used by this code is O(n/2), as we are creating a sublist with half of the original list size.
Last Updated :
23 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...