Python | K Divided Indices List
Last Updated :
13 Apr, 2023
Sometimes, while working with Python lists, we can have a problem in which we wish to find Modulo K elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let’s discuss certain way to find indices of modulo K elements.
Method #1 : Using loop This is brute force method in which this task can be performed. In this, we check for % K element in list and append its index accordingly.
Python3
test_list = [ 5 , 6 , 10 , 4 , 7 , 1 , 19 ]
print ( "The original list is : " + str (test_list))
K = 5
res = []
for idx, ele in enumerate (test_list):
if ele % K = = 0 :
res.append(idx)
print ( "Indices list modulo K elements is : " + str (res))
|
Output
The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list modulo K elements is : [0, 2]
Time Complexity: O(n*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 list comprehension This is the shorthand by which this task can be performed. This method works in similar way as the above method. The difference is that it’s a one liner.
Python3
test_list = [ 5 , 6 , 10 , 4 , 7 , 1 , 19 ]
print ( "The original list is : " + str (test_list))
K = 5
res = [idx for idx, ele in enumerate (test_list) if ele % K = = 0 ]
print ( "Indices list modulo K elements is : " + str (res))
|
Output
The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list modulo K elements is : [0, 2]
Time Complexity: O(n) where n is the number of elements in the test_list. The list comprehension is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the test list.
Method #3 : Using Filter and Lambda function
Python3
test_list = [ 5 , 6 , 10 , 4 , 7 , 1 , 19 ]
print ( "The original list is : " + str (test_list))
K = 5
res = list ( filter ( lambda x : test_list[x[ 0 ]] % K = = 0 , enumerate (test_list)))
res = [ele[ 0 ] for ele in res]
print ( "Indices list modulo K elements is : " + str (res))
|
Output
The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list modulo K elements is : [0, 2]
Time complexity: O(n)
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...