Open In App

Python – Product of Selective Tuple Keys

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while using a list of tuples, we come across a problem in which we have a certain list of keys and we just need the product of values of those keys from the list of tuples. This has a utility in rating or product of specific entities. Let’s discuss certain ways in which this can be done. 

Method #1: Using dict() + loop + get() + list comprehension

We can perform this particular task by first, converting the list into the dictionary and then employing list comprehension to get the value of specific keys using the get function. The product of values is performed using a loop. 

Python3




# Python3 code to demonstrate
# Product of Selective Tuple Keys
# using dict() + get() + list comprehension + loop
 
# getting Product
def prod(val):
   
    res = 1
   
  for ele in val:
        res *= ele
    return res
 
 
# Initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
 
# Initializing selection list
select_list = ['Nikhil', 'Akshat']
 
# Printing original list
print("The original list is: "+ str(test_list))
 
# Printing selection list
print("The selection list is : " + str(select_list))
 
# Product of Selective Tuple Keys
# using dict() + get() + list comprehension + loop
temp = dict(test_list)
res = prod([temp.get(i, 0) for i in select_list])
 
# Printing the result
print("The selective values product of keys : " + str(res))


Output

The original list is: [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3

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

Method #2: Using next() + loop + list comprehension

This particular problem can be solved using the next function which performs the iteration using the iterators and hence more efficient way to achieve a possible solution. The product of values is performed using loop. 

Python3




# Python3 code to demonstrate
# Product of Selective Tuple Keys
# using next() + list comprehension + loop
 
# Function to get the product
def prod(val):
 
    res = 1
 
  for ele in val:
        res *= ele
    return res
 
 
# Initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
 
# Initializing selection list
select_list = ['Nikhil', 'Akshat']
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Printing selection list
print("The selection list is : " + str(select_list))
 
# Product of Selective Tuple Keys
# using next() + list comprehension + loop
res = prod([next((sub[1] for sub in test_list if sub[0] == i), 0)
            for i in select_list])
 
# Printing the result
print("The selective values product of keys : " + str(res))


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3

Time Complexity: O(N * M), where n is the length of the test_list and m is the length of the select_list.
Auxiliary Space: O(M), where m is the length of the select_list. 

Method #3: Using for loop and in operator

Python3




# Python3 code to demonstrate
# Product of Selective Tuple Keys
 
# Initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
 
# Initializing selection list
select_list = ['Nikhil', 'Akshat']
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Printing selection list
print("The selection list is : " + str(select_list))
 
# Product of Selective Tuple Keys
res = 1
for i in test_list:
    if i[0] in select_list:
        res *= i[1]
 
# Printing result
print("The selective values product of keys : " + str(res))


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3

Time Complexity: O(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 #4 : Using map() and lambda() functions

Python3




def prod(val):
   
    # Initialize a variable to store the product of values
    res = 1
    # Loop through each value in the input list
    for ele in val:
        # Multiply the current product by the current value
        res *= ele
    # Return the final product
    return res
   
# Initialize a list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
 
# Initialize a list of selected keys
select_list = ['Nikhil', 'Akshat']
 
# Create a dictionary from the list of tuples
temp = dict(test_list)
 
# Calculate the product of values of selected keys
# using a map and lambda function
  
# Printing original list
print("The original list is : " + str(test_list))
  
# Printing selection list
print("The selection list is : " + str(select_list))
  
result = prod(map(lambda x: temp.get(x, 0), select_list))
 
# Print the result
print("The selective values product of keys : " + str(result))
 
#This code is contributed by Jyothi pinjala


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3

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

Method #5: Using functools.reduce()+operator.mul+for loop

Python3




# Python3 code to demonstrate
# Product of Selective Tuple Keys
 
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
 
# initializing selection list
select_list = ['Nikhil', 'Akshat']
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing selection list
print("The selection list is : " + str(select_list))
 
# Product of Selective Tuple Keys
res = []
for i in test_list:
    if i[0] in select_list:
        res.append(i[1])
 
from functools import reduce
import operator
res1=reduce(operator.mul,res,1)
 
# printing result
print("The selective values product of keys : " + str(res1))


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3

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

Method #6:Using Recursion

This code defines a function selective_product(tuples, selection) that takes a list of tuples and a list of strings selection as input and returns the product of values in the tuples that have keys that appear in the selection list. The function recursively traverses the input list of tuples, checks if the key of the current tuple is in the selection list, and if so, multiplies its value with the product of the remaining tuples. If the key is not in the selection list, the function recurses on the remaining tuples.

The code then defines an example input list of tuples test_list and a selection list select_list, calls the selective_product function on them, and prints the resulting product.

Python3




def selective_product(tuples, selection):
    if len(tuples) == 0:
        return 1
    elif tuples[0][0] in selection:
        return tuples[0][1] * selective_product(tuples[1:], selection)
    else:
        return selective_product(tuples[1:], selection)
 
# Example usage
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
 
# printing selection list
print("The selection list is : " + str(select_list))
res = selective_product(test_list, select_list)
print("The selective values product of keys : " + str(res))
#This code is contributed Vinay pinjala.


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3

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

Time complexity:

The function recurses over the input list of tuples. In the worst case, it needs to check each tuple once, so the worst-case time complexity is O(n), where n is the length of the input list.
Multiplying the values of selected tuples takes constant time, and the in operator used to check if the key is in the selection list also takes constant time.
Therefore, the overall time complexity of this function is O(n), where n is the length of the input list.

Auxiliary Space:

The function uses recursion to traverse the input list of tuples. In the worst case, the recursion depth is equal to the length of the input list, so the worst-case space complexity is O(n), where n is the length of the input list.
The function uses a constant amount of additional space for storing the selection list and temporary variables.
Therefore, the overall space complexity  is O(n)

Method #5: Using list comprehension with conditional and reduce()

This method uses list comprehension to filter out the tuples whose first element is not in the select_list. Then it uses reduce() with the operator.mul function to multiply all the second elements of the filtered tuples.

Python3




from functools import reduce
import operator
 
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
select_list = ['Nikhil', 'Akshat']
 
res = [tup[1] for tup in test_list if tup[0] in select_list]
res1 = reduce(operator.mul, res, 1)
 
print("The selective values product of keys : " + str(res1))


Output

The selective values product of keys : 3

The time complexity of this code is O(n), where n is the length of the test_list. 
The auxiliary space complexity is O(k), where k is the length of the filtered list obtained from the list comprehension. 

Method 8 : Using filter() and reduce()

Use the filter() function to create a new list of tuples where the key of each tuple is in the selection list.
Use the reduce() function from the functools module to multiply the values of the tuples in the new list.
Return the result.

Python3




import functools
 
def selective_product(tuples, selection):
    selected_tuples = filter(lambda x: x[0] in selection, tuples)
    selected_values = [t[1] for t in selected_tuples]
    result = functools.reduce(lambda x, y: x * y, selected_values, 1)
    return result
 
# Example usage
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
 
# printing selection list
print("The selection list is : " + str(select_list))
res = selective_product(test_list, select_list)
print("The selective values product of keys : " + str(res))
# Output: The selective values product of keys : 3


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3

Time complexity: O(n), where n is the length of the tuples list.
Auxiliary space: O(k), where k is the number of tuples whose keys are in the selection list.



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