Python program to Test if all y occur after x in List
Last Updated :
27 Apr, 2023
Given a List, test if all occurrences of y are after the occurrence of x in the list.
Input : test_list = [4, 5, 6, 2, 4, 5, 2, 9], x, y = 6, 2
Output : True
Explanation : All occurrences of 2 are after 6, hence true.
Input : test_list = [4, 2, 5, 6, 2, 4, 5, 2, 9], x, y = 6, 2
Output : False
Explanation : All occurrences of 2 are not after 6, hence true.
Method #1 : Using loop + index()
In this, we check for an index of x in the list, and then run a loop to get the occurrence of y, if any y occurs before x index, the result is False.
Python3
test_list = [ 4 , 5 , 6 , 2 , 4 , 5 , 2 , 9 ]
print ( "The original list is : " + str (test_list))
x, y = 6 , 2
xidx = test_list.index(x)
res = True
for idx, ele in enumerate (test_list):
if ele = = y and idx < xidx:
res = False
break
print ( "Do all y occur after x : " + str (res))
|
Output:
The original list is : [4, 5, 6, 2, 4, 5, 2, 9]
Do all y occur after x : True
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using all() + index()
In this, we test for all the indices of y using all(), and index() is used to get the index of x in the list.
Python3
test_list = [ 4 , 5 , 6 , 2 , 4 , 5 , 2 , 9 ]
print ( "The original list is : " + str (test_list))
x, y = 6 , 2
xidx = test_list.index(x)
res = all (idx > xidx for idx, ele in enumerate (test_list) if ele = = y)
print ( "Do all y occur after x : " + str (res))
|
Output:
The original list is : [4, 5, 6, 2, 4, 5, 2, 9]
Do all y occur after x : True
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), no extra space required
Method #3 : Using count(),index() methods
Approach:
- Store the count of y in test_list in a(using count())
- Find the index of x in test_list and store in b
- Slice the test_list from b to end and find the count of y in it and store in z(using count())
- Check if a==z, if yes which means y occurs after all x in list then set res to True, otherwise set res to False
- Display res
Python3
test_list = [ 4 , 5 , 6 , 2 , 4 , 5 , 2 , 9 ]
print ( "The original list is : " + str (test_list))
x, y = 6 , 2
a = test_list.count(y)
b = test_list.index(x)
z = test_list[b:].count(y)
res = a = = z
print ( "Do all y occur after x : " + str (res))
|
Output
The original list is : [4, 5, 6, 2, 4, 5, 2, 9]
Do all y occur after x : True
Time Complexity : O(N) N – length of test_list.
Auxiliary Space: O(1) because only a single variable is used to store the result.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...