Open In App

Python | Multiplying Selective Values

Improve
Improve
Like Article
Like
Save
Share
Report

Accessing an element from its index is easier task in python, just using the [] operator in a list does the trick. But in certain situations we are presented with tasks when we have more than once indices and we need to get all the elements corresponding to those indices and its product. Lets discuss certain ways to achieve this task. 

Method #1 : Using List comprehension + loop

This task is easy to perform with a loop, and hence shorthand for it is the first method to start with this task. Iterating over the index list to get the corresponding elements from list into new list is brute method to perform this task. The task of performing product is performed by loop. 

Approach:

  1. Define a function named prod that takes a list of values as input.
  2. Initialize a variable res to 1.
  3. Traverse the list using a for loop and multiply each element to res.
  4. Return the final value of res.
  5. Initialize two lists test_list and index_list with some values.
  6. Print the original lists test_list and index_list.
  7. Using list comprehension and a for loop, create a new list res_list that contains only the values from test_list at the indices specified by index_list.
  8. Call the prod function on the res_list to get the product of the selected values.
  9. Print the resulting product.

Python3




# Python3 code to demonstrate
# Multiplying Selective Values
# using list comprehension + loop
 
# getting Product
 
 
def prod(val):
    res = 1
    for ele in val:
        res *= ele
    return res
 
 
# initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
 
# printing original lists
print("Original list : " + str(test_list))
print("Original index list : " + str(index_list))
 
# using list comprehension + loop to
# Multiplying Selective Values
res_list = [test_list[i] for i in index_list]
res = prod(res_list)
 
# printing result
print("Resultant product : " + str(res))


Output : 

Original list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant product : 320

Time complexity: O(k), where k is the length of the index_list.
Auxiliary space: O(k), since we create a new list of length k to store the selected elements of test_list.

Method #2: Using map() + __getitem__ + loop

Yet another method to achieve this particular task is to map one list with other and get items of indexes and get corresponding matched elements from the search list. This is quite a quick way to perform this task. The task of performing the product is performed by the loop. 

Python3




# Python3 code to demonstrate
# Multiplying Selective Values
# using map() + __getitem__ + loop
 
# getting Product
 
 
def prod(val):
    res = 1
    for ele in val:
        res *= ele
    return res
 
 
# initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
 
# printing original lists
print("Original list : " + str(test_list))
print("Original index list : " + str(index_list))
 
# using map() + __getitem__ + loop to
# Multiplying Selective Values
res_list = prod(list(map(test_list.__getitem__, index_list)))
 
# printing result
print("Resultant product : " + str(res_list))


Output : 

Original list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant product : 320

Time Complexity: O(n*n) where n is the number of elements in the test_list. The map() + __getitem__ + loop is used to perform the task and it takes O(n*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 numpy library

Note: Install numpy module using the command “pip install numpy”

Another approach to perform this task is by using numpy library. Numpy provides the feature to access the elements from the array using the index and hence it can be used to access the elements in the array based on the index list.

Python3




import numpy as np
 
# initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
 
# printing original lists
print("Original list : " + str(test_list))
print("Original index list : " + str(index_list))
 
# using numpy to multiply selective values
res_list = np.prod(np.array(test_list)[index_list])
 
# printing result
print("Resultant product : ", res_list)


Output:

Original list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant product :  320

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4: Using reduce() function from functools module

the reduce() function from the functools module is used to compute the product of the selected values from the test_list based on the indices present in the index_list. The lambda function inside the reduce() function is used to compute the product of the values. The initial value of 1 is used as the starting value for the reduce() function.

Python3




# Python3 code to demonstrate
# Multiplying Selective Values
# using reduce() function
 
from functools import reduce
 
# getting Product
 
 
def prod(val):
    res = 1
    for ele in val:
        res *= ele
    return res
 
 
# initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
 
# printing original lists
print("Original list : " + str(test_list))
print("Original index list : " + str(index_list))
 
# using reduce() function to Multiplying Selective Values
res = reduce(lambda x, i: x * test_list[i], index_list, 1)
 
# printing result
print("Resultant product : " + str(res))


Output

Original list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant product : 320

Time complexity: O(N), where N is the length of the index_list.
Auxiliary space: O(1), as it only uses a constant amount of extra space to store the intermediate result and the loop variables.

Method #5: Using a loop to filter values and then using the built-in prod() function to get the product of the filtered values.

The given code initializes two lists test_list and index_list. It then computes the product of elements in test_list at the indices specified in index_list using a loop to filter values and then multiplying them using the prod() function. Finally, it prints the original lists and the resultant product.

In summary, the code multiplies selective values in a list based on the indices provided in another list.

Python3




# initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
 
# using a loop to filter values and then using the built-in prod() function to get the product
res = 1
for i in index_list:
    if i < len(test_list):
        res *= test_list[i]
 
# printing original lists
print("Original list : " + str(test_list))
print("Original index list : " + str(index_list))
 
# printing result
print("Resultant product : " + str(res))


Output

Original list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant product : 320

Time complexity: O(k), where k is the length of the index_list. 
Auxiliary space: O(1), since it uses a constant amount of additional memory (one variable res) that does not depend on the input size.

Method #6: Using itertools module’s compress() function

This method uses the compress() function from the itertools module to filter out the elements of the original list based on the given indices list. It then computes the product of the filtered list using the prod() function.

  • Import the necessary modules: itertools and functools.
  • Define a function prod() that takes a list of numbers and returns their product using reduce() and a lambda function.
  • Initialize the original list test_list and the indices list index_list.
  • Print the original lists.
  • Use compress() function from the itertools module to filter the elements of the original list based on the given indices list. This is done by creating a list of boolean values where each element corresponds to the membership of the corresponding index in the test_list in the index_list. The compress() function then returns a list of values from the original list where the corresponding element in the boolean list is True.
  • Convert the output of compress() to a list.
  • Compute the product of the filtered list using the prod() function.
  • Print the resultant product.

Python3




# Python3 code to demonstrate
# Multiplying Selective Values
# using itertools.compress() function
 
from itertools import compress
from functools import reduce
 
# getting Product
 
 
def prod(val):
    return reduce(lambda x, y: x*y, val)
 
 
# initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
 
# printing original lists
print("Original list : " + str(test_list))
print("Original index list : " + str(index_list))
 
# using itertools.compress() to filter values based on indices
filtered_list = list(
    compress(test_list, [i in index_list for i in range(len(test_list))]))
 
# getting product of filtered values using prod() function
res = prod(filtered_list)
 
# printing result
print("Resultant product : " + str(res))


Output

Original list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant product : 320

Time complexity: O(n), where n is the length of the original list.
Auxiliary space: O(m), where m is the length of the filtered list.

Method#7: Using Recursive Method:

Steps:

  1. In this recursive method, the idea is to use the input lists test_list and index_list. The test_list contains the numbers to multiply, and the index_list contains the indices of the numbers to multiply.
  2. In the base case, when index_list is empty, return 1 since multiplying it won’t affect the product.
  3. In the recursive case, return the product of the first element of test_list at the index specified in index_list, and the result of recursively calling multiply_selective_values with test_list and the rest of index_list.
  4. Finally, call the multiply_selective_values function with the input lists to get the result.

Python3




# Python program for the above approach
 
# Function to multiply the selective
# value
def multiply_selective_values(test_list, index_list):
 
    # Base Case
    if len(index_list) == 0:
        return 1
 
    # Recursive Case
    return test_list[index_list[0]] * multiply_selective_values(test_list, index_list[1:])
 
 
# Driver Code
 
# Initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
 
# Print original lists
print("Original list : " + str(test_list))
print("Original index list : " + str(index_list))
 
res = multiply_selective_values(test_list, index_list)
 
# Print result
print("Resultant product : " + str(res))


Output

Original list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant product : 320

The time complexity of the recursive method is O(K), where K is the number of indices in `index_list`. This is because each recursive call removes the first element of `index_list` until the base case is reached. In the base case, there are no more recursive calls, so the time complexity is constant.

The space complexity of the recursive method is O(K), as well, because each recursive call creates a new stack frame that stores the first element of `index_list`. The space required for each stack frame is constant, so the total space required is proportional to the number of recursive calls.



Last Updated : 13 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads