Python | K Value Indices Product
Last Updated :
19 Apr, 2023
Usually, we require to find the index, in which the particular value is located. There are many method to achieve that, using index() etc. But sometimes require to find all the indices of a particular value in case it has multiple occurrences in list and compute their product. Lets discuss certain ways to do so.
Method #1 : Naive Method We can achieve this task by iterating through the list and check for that value and just append the value index in new list and print that. This is the basic brute force method to achieve this task. The task of performing product is done by loop.
Python3
test_list = [ 1 , 3 , 4 , 3 , 6 , 7 , 3 ]
print ("Original list : " + str (test_list))
K = 3
res = 1
for i in range ( 0 , len (test_list)) :
if test_list[i] = = K :
res * = i
print ("K Value indices product is : " + str (res))
|
Output :
Original list : [1, 3, 4, 3, 6, 7, 3]
K Value indices product is : 18
Method #2 : Using enumerate() + loop Using enumerate() we can achieve the similar task, this is slightly faster technique than above and hence is recommended to be used over the list comprehension technique. The task of performing product is done by loop.
Python3
def prod(val) :
res = 1
for ele in val:
res * = ele
return res
test_list = [ 1 , 3 , 4 , 3 , 6 , 7 , 3 ]
print ("Original list : " + str (test_list))
K = 3
res = prod([i for i, value in enumerate (test_list) if value = = K])
print ("K Value indices product is : " + str (res))
|
Output :
Original list : [1, 3, 4, 3, 6, 7, 3]
K Value indices product is : 18
Method#3:using exception handling
Approach
this approach iterates through the list and calculates the product of indices, but it uses a try-except block to check if the value k exists in the list. If it doesn’t, it returns 0.
Algorithm
1. Initialize the product variable to the index of the first occurrence of k in the list.
2. If k is not found in the list, return 0.
3. Iterate through the list starting from the index of the first occurrence of k.
4. For each element in the list, if it is equal to k, multiply the current value of the product by its index.
5. Return the final value of the product.
Python3
def k_value_indices_product(lst, k):
try :
product = lst.index(k)
except ValueError:
return 0
for i in range (product + 1 , len (lst)):
if lst[i] = = k:
product * = i
return product
lst = [ 1 , 3 , 4 , 3 , 6 , 7 , 3 ]
k = 3
print (k_value_indices_product(lst, k))
|
Time complexity: O(n), where n is the length of the list. This is because it iterates through the list at most twice: once to find the index of the first occurrence of k, and once more to calculate the product of indices.
Space complexity: O(1) since it only uses a few variables that do not depend on the size of the input list.
Method #4: Using numpy.where() function
Step-by-step approach:
- Import numpy library.
- Initialize the test_list.
- Print the initial list.
- Initialize the value of K.
- Use numpy.where() function to get indices of elements with value K.
- Pass the obtained indices to numpy.prod() function to get the product of all the indices.
- Print the result
Python3
import numpy as np
test_list = [ 1 , 3 , 4 , 3 , 6 , 7 , 3 ]
print ( "Original list : " + str (test_list))
K = 3
indices = np.where(np.array(test_list) = = K)[ 0 ]
res = np.prod(indices)
print ( "K Value indices product is : " + str (res))
|
OUTPUT:
Original list : [1, 3, 4, 3, 6, 7, 3]
K Value indices product is : 18
Time complexity: O(n)
Auxiliary space: O(1) (in-place) or O(n) (if the output list is created separately
Method #5: Using a list comprehension and the reduce() function from the functools module.
Steps:
- Import the reduce function from the functools module.
- Define the function find_k_indices_product that takes a list lst and an integer k as input.
- Inside the function, use a list comprehension to create a list of indices where the value is equal to k.
- If the list is empty, return 0.
- If the list is not empty, use the reduce function to multiply all the indices together and return the product.
Python3
from functools import reduce
def find_k_indices_product(lst, k):
indices = [i for i, value in enumerate (lst) if value = = k]
if not indices:
return 0
return reduce ( lambda x, y: x * y, indices)
test_list = [ 1 , 3 , 4 , 3 , 6 , 7 , 3 ]
K = 3
print ( "Original list : " + str (test_list))
print ( "K Value indices product is : " + str (find_k_indices_product(test_list, K)))
|
Output
Original list : [1, 3, 4, 3, 6, 7, 3]
K Value indices product is : 18
Time complexity: O(n)
Auxiliary space: O(1)
Method #6: Using heapq :
Algorithm:
- Create an empty list indices.
- Loop over the elements and indices of lst, appending each index to indices if its corresponding value is equal to k.
- If indices is empty, return 0.
- Negate all the elements of indices.
- Use heapify to turn indices into a min-heap.
- Pop the smallest element from the heap, negate it, and set it as the initial value of result.
- While the heap is not empty, pop the smallest element, negate it, and multiply it with result.
- Return result.
Python3
import heapq
def find_k_indices_product(lst, k):
indices = [ - i for i, value in enumerate (lst) if value = = k]
if not indices:
return 0
heapq.heapify(indices)
result = - heapq.heappop(indices)
while indices:
result * = - heapq.heappop(indices)
return result
test_list = [ 1 , 3 , 4 , 3 , 6 , 7 , 3 ]
K = 3
print ( "Original list : " + str (test_list))
print ( "K Value indices product is : " + str (find_k_indices_product(test_list, K)))
|
Output
Original list : [1, 3, 4, 3, 6, 7, 3]
K Value indices product is : 18
Time complexity:
The time complexity of the modified find_k_indices_product function using heapq is O(N log K), where N is the length of the input list and K is the number of indices where the value equals k. This is because we need to loop over the input list once to find the indices where the value equals k, and then use the heapq module to sort those indices in ascending order, which takes O(K log K) time. Finally, we loop over the sorted indices to calculate the product, which takes O(K) time.
Space complexity:
The space complexity of the modified find_k_indices_product function using heapq is O(N), where N is the length of the input list. This is because we create a list of negative indices that correspond to the locations of the value k in the input list, which could potentially take up all of the memory. However, since we use heapq to sort these indices in-place, the actual amount of memory used is limited to the size of the heap (i.e., O(K)). The remaining variables used in the function (i.e., result and K) take up constant space.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...