Open In App

Python – Indices of atmost K elements in list

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices less than or equal than particular number, but this approach fails in case of duplicate numbers. Let’s discuss certain ways in which this problem can be successfully solved. 

Method #1 : Using loop This problem can easily be solved using loop with a brute force approach in which we can just check for the index as we iterate and append it in a new list as we proceed forward. 

Python3




# Python3 code to demonstrate
# Atmost K element indices
# using loop
 
# initializing list
test_list = [12, 11, 7, 15, 8, 18]
 
# printing original list
print("The original list : " + str(test_list))
 
# using loop
# Atmost K element indices
res = []
for idx in range(0, len(test_list)) :
    if test_list[idx] <= 11:
        res.append(idx)
 
# print result
print("The list of indices at most 11 : " + str(res))


Output : 

The original list : [12, 11, 7, 15, 8, 18]
The list of indices at most 11 : [1, 2, 4]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(k), where k is the number of indices that satisfy the condition.

Method #2 : Using list comprehension + enumerate() The combination of these two function can also perform this particular task efficiently and in one line. The enumerate function is used to get element and its index simultaneously. 

Python3




# Python3 code to demonstrate
# Atmost K element indices
# using list comprehension + enumerate()
 
# initializing list
test_list = [12, 11, 7, 15, 8, 18]
 
# printing original list
print("The original list : " + str(test_list))
 
# using list comprehension + enumerate()
# Atmost K element indices
res = [idx for idx, val in enumerate(test_list) if val <= 11]
 
# print result
print("The list of indices at most 11 : " + str(res))


Output : 

The original list : [12, 11, 7, 15, 8, 18]
The list of indices at most 11 : [1, 2, 4]

Time complexity: O(n), where n is the size of the input list.
Auxiliary space: O(k), where k is the number of indices that satisfy the condition (i.e., val <= 11).

 Method 3: Using the filter function

Create a lambda function that takes an index x and returns True if the corresponding element in the test_list is less than or equal to 11. Then, we apply the filter function to the range of indices of the test_list and convert the result to a list.

Python3




# Python3 code to demonstrate
# Atmost K element indices
# using filter function
 
# initializing list
test_list = [12, 11, 7, 15, 8, 18]
 
# printing original list
print("The original list : " + str(test_list))
 
# using filter function
# Atmost K element indices
res = list(filter(lambda x: test_list[x] <= 11, range(len(test_list))))
 
# print result
print("The list of indices at most 11 : " + str(res))


Output

The original list : [12, 11, 7, 15, 8, 18]
The list of indices at most 11 : [1, 2, 4]

Time Complexity: O(n)

  • The lambda function is called n times (where n is the length of test_list).
  • The filter function is also called n times in the worst case, as it needs to iterate through all the indices.

Auxiliary Space: O(k)

  • The filter function returns a list with at most k elements, where k is the number of elements in test_list that are less than or equal to 11.
  • Therefore, the space complexity is proportional to k.

Method 4: Using Recursive method.

Algorithm:

  1. Define a function indices_atmost_k that takes in a list test_list, a value k, an index idx (optional, default=0), and a list res (optional, default=[]).
  2. If idx is equal to the length of test_list, return res (base case).
  3. If the element at the current index idx of test_list is less than or equal to k, append idx to res.
  4. Recursively call indices_atmost_k with the updated idx (idx+1) and res.
  5. Return the final value of res after all recursive calls have finished.

Python3




def indices_atmost_k(test_list, k, idx=0, res=[]):
    if idx == len(test_list):
        return res
    if test_list[idx] <= k:
        res.append(idx)
    return indices_atmost_k(test_list, k, idx+1, res)
test_list = [12, 11, 7, 15, 8, 18]
k = 11
res = indices_atmost_k(test_list, k)
print("The original list : " + str(test_list))
 
print("The list of indices at most", k, ":", res)


Output

The original list : [12, 11, 7, 15, 8, 18]
The list of indices at most 11 : [1, 2, 4]

Time Complexity: O(n), where n is the length of test_list. We visit each element of test_list exactly once, so the time complexity is proportional to the length of the input list.

Auxiliary Space: O(n), where n is the length of test_list. This is because we need to store the list of indices in res, which can have a maximum length of n if all elements in the input list satisfy the condition of being at most k. Additionally, the recursive calls use up memory on the call stack, which can go up to a depth of n if all elements satisfy the condition.

Method 5: Using a generator function

  • Define a generator function named “atmost_k_indices()” that takes in the same parameters as the previous methods (test_list and k).
  • Use a for loop to iterate over each index in the range of the length of the test_list.
  • If the value of the element at the current index is less than or equal to k, yield the index.
  • Call the generator function and store the result in a variable named “res” using a list comprehension.
  • Print the original list and the list of indices at most k using the variables “test_list” and “res”, respectively.

Python3




def atmost_k_indices(test_list, k):
    for i in range(len(test_list)):
        if test_list[i] <= k:
            yield i
 
test_list = [12, 11, 7, 15, 8, 18]
k = 11
res = [idx for idx in atmost_k_indices(test_list, k)]
print("The original list : " + str(test_list))
print("The list of indices at most", k, ":", res)


Output

The original list : [12, 11, 7, 15, 8, 18]
The list of indices at most 11 : [1, 2, 4]

Time complexity: O(n)
Auxiliary space: O(1)

Method 5 : using the Numpy library. 

step-by-step approach 

  • Step 1: Import the Numpy library using the import numpy as np statement.
  • Step 2: Define a function called atmost_k_indices_np that takes two parameters test_list and k.
  • Step 3: Convert the test_list into a numpy array using the np.array() method.
  • Step 4: Use the np.where() method to find the indices where the elements in the numpy array are less than or equal to k. This method returns a tuple, and we extract the first element (the indices) using [0].
  • Step 5: Return the list of indices found in Step 4.
  • Step 6: Define the test_list and k values as given in the problem.
  • Step 7: Call the atmost_k_indices_np function with the test_list and k values.
  • Step 8: Store the result in a variable called res.
  • Step 9: Print the original test_list and the list of indices that are less than or equal to k.

Python3




import numpy as np
 
def atmost_k_indices_np(test_list, k):
    return np.where(np.array(test_list) <= k)[0]
 
test_list = [12, 11, 7, 15, 8, 18]
k = 11
res = atmost_k_indices_np(test_list, k)
print("The original list : " + str(test_list))
print("The list of indices at most", k, ":", res)


OUTPUT :
The original list : [12, 11, 7, 15, 8, 18]
The list of indices at most 11 : [1 2 4]

Time complexity: O(n), where n is the length of the given test_list.
Auxiliary space: O(n), where n is the length of the given test_list 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads