Open In App

Python | Cartesian product of string elements

Last Updated : 09 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python strings, we can have problem when we have data in a string that is a comma or any delim separated. We might want to perform a cartesian product with other similar strings to get all possible pairs of data. Let us discuss certain ways in which this task can be performed. 

Method #1 : Using list comprehension + split()

This task can be performed using list comprehension. In this, we perform the task of extracting individual elements using split(). The task of list comprehension is to form pairs. 

Python3




# Python3 code to demonstrate working of
# Cartesian product of string elements
# Using split() + list comprehension
 
# Initializing strings
test_str1 = "gfg, is, best"
test_str2 = "for, all, geeks"
 
# Printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
 
# Cartesian product of string elements
# Using split() + list comprehension
res = [sub1 + sub2 for sub1 in test_str1.split(", ")
       for sub2 in test_str2.split(", ")]
 
# Printing result
print("Cartesian product list : " + str(res))


Output : 

The original string 1 is : gfg, is, best
The original string 2 is : for, all, geeks
Cartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks']

Method #2: Using List comprehension + product()

The combination of the above functions can be used to perform this task. In this, we employ product() in place of nested comprehension to perform the task of pairing. 

Python3




# Python3 code to demonstrate working of
# Cartesian product of string elements
# Using product() + list comprehension
 
from itertools import product
 
# initializing strings
test_str1 = "gfg, is, best"
test_str2 = "for, all, geeks"
 
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
 
# Cartesian product of string elements
# Using product() + list comprehension
res = [sub1 + sub2 for sub1,
       sub2 in product(test_str1.split(", "), test_str2.split(", "))]
 
# printing result
print("Cartesian product list : " + str(res))


Output : 

The original string 1 is : gfg, is, best
The original string 2 is : for, all, geeks
Cartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks']

Method 3: Using nested for loops

  1. Create two lists by splitting the input strings using the split() method.
  2. Initialize an empty list to store the cartesian product of the strings.
  3. Use two nested for loops to iterate through each element of the two lists and concatenate them.
  4. Append the concatenated string to the empty list created in step 2.
  5. Return the list of cartesian product strings.

Python3




# Python3 code to demonstrate working of
# Cartesian product of string elements
# using nested for loops
 
# initializing strings
test_str1 = "gfg, is, best"
test_str2 = "for, all, geeks"
 
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
 
# Creating two lists by splitting input strings
list1 = test_str1.split(", ")
list2 = test_str2.split(", ")
 
# initializing empty list to store cartesian product of strings
cartesian_product = []
 
# Using nested for loops to iterate through each element of the two lists and concatenate them.
for word1 in list1:
    for word2 in list2:
        cartesian_product.append(word1 + word2)
 
# printing result
print("Cartesian product list : " + str(cartesian_product))


Output

The original string 1 is : gfg, is, best
The original string 2 is : for, all, geeks
Cartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks']

Time Complexity: O(n^2) 
The nested for loop iterates through all the elements of both the lists, so the time complexity will be O(n^2), where n is the length of the input lists.

Auxiliary Space: O(n^2) 
The space required by this method is O(n^2) because we are storing all the possible combinations in the cartesian_product list.

Method #4: Using itertools.product()

Step-by-step approach:

  1. Import the itertools module which provides various tools for creating iterators.
  2. Initialize the strings
  3. Split the strings into lists using the split() method and strip any whitespaces
  4. Use the product() function from itertools to generate the Cartesian product of the two lists
  5. Flatten the resulting list of tuples into a single list
  6. Print the final result

Python3




# Python3 code to demonstrate working of
# Cartesian product of string elements
# using itertools.product()
 
# importing itertools module
from itertools import product
 
# initializing strings
test_str1 = "gfg, is, best"
test_str2 = "for, all, geeks"
 
# Splitting strings into lists
list1 = [word.strip() for word in test_str1.split(',')]
list2 = [word.strip() for word in test_str2.split(',')]
 
# Using itertools.product() to generate Cartesian product
cartesian_product = list(product(list1, list2))
 
# Flattening the list of tuples into a single list
cartesian_product = [word1 + word2 for word1, word2 in cartesian_product]
 
# printing result
print("Cartesian product list : " + str(cartesian_product))


Output

Cartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks']

The time complexity of this method is O(n*m), where n is the length of the first list and m is the length of the second list. 
The auxiliary space required by this method is O(n*m), as we store all possible combinations of elements from both lists in the cartesian_product list.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads