Tuesday 11 October 2022

Itertools.Product() in Python

 In the terms of Mathematics Cartesian Product of two sets is defined as the set of all ordered pairs (a, b) where a belongs to A and b belongs to B. Consider the below example for better understanding.


Examples:

Input : arr1 = [1, 2, 3] 
arr2 = [5, 6, 7] 
Output : [(1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)] 
Input : arr1 = [10, 12] 
arr2 = [8, 9, 10] 
Output : [(10, 8), (10, 9), (10, 10), (12, 8), (12, 9), (12, 10)] 
 

The above solution can be done by looping but we will use a special Python library itertools.product() for finding the Cartesian Product. Let’s go through the working and use cases of this Python library.

No comments:

Post a Comment