![]() |
VOOZH | about |
Sometimes, while working with Python records, we can have a problem in which we need to perform cross multiplication of list of tuples. This kind of application is popular in web development domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + zip() The combination of the above functionalities can be used to perform this particular task. In this, we iterate through the list using list comprehension and the multiplication across lists is performed with the help of zip().
The original list 1 : [(2, 4), (6, 7), (5, 1)] The original list 2 : [(5, 4), (8, 10), (8, 14)] The multiplication across lists is : [(10, 16), (48, 70), (40, 14)]
Time complexity: O(n), where n is the length of the lists test_list1 and test_list2.
Auxiliary space: O(n), where n is the length of the lists test_list1 and test_list2, since the result is stored in a new list.
Method #2 : Using loop + zip() + map() This is yet another way to perform this task. This is similar to above method, the difference is that multiplication is performed by explicit function and extending logic to each element is done by map().
The original list 1 : [(2, 4), (6, 7), (5, 1)] The original list 2 : [(5, 4), (8, 10), (8, 14)] The multiplication across lists is : [(10, 16), (48, 70), (40, 14)]
The time complexity of this code is O(nm), where n is the length of test_list1 and m is the length of test_list2.
The space complexity of this code is O(n), where n is the length of test_list1.
Method #3 : Using itertools.starmap()
The itertools module of Python provides us a starmap() function which is used to apply a given function to each of the tuple of an iterable. This can be used to perform this task.
The original list 1 : [(2, 4), (6, 7), (5, 1)] The original list 2 : [(5, 4), (8, 10), (8, 14)] The multiplication across lists is : [(10, 16), (48, 70), (40, 14)]
Time Complexity: O(n)
Space Complexity: O(n)
Method#4: using max() + zip() + recursion.
The original list 1 : [(2, 4), (6, 7), (5, 1)] The original list 2 : [(5, 4), (8, 10), (8, 14)] The multiplication across lists is : [(10, 16), (48, 70), (40, 14)]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #6: Using NumPy (without transposing)
Here's another approach using NumPy, but without transposing the result. Instead, we can directly reshape the result array to get the desired output format.
Steps:
OUTPUT: The multiplication across lists is : [[10, 16], [48, 70], [40, 14]]
Time Complexity: O(n)
Auxiliary Space: O(n)