Python | Union Operation in two Strings
Last Updated :
16 May, 2023
One of the string operation can be computing the union of two strings. This can be useful application that can be dealt with. This article deals with computing the same through different ways.
Method 1 : Naive Method The task of performing string union can be computed by naive method by creating an empty string and checking for new occurrence of character common to both string and not common strings and appending it and hence computing the new union string. This can be achieved by loops and if/else statements.
Python3
# Python 3 code to demonstrate
# Union Operation in two Strings
# using naive method
# initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
# Printing initial strings
print ("The original string 1 is : " + test_str1)
print ("The original string 2 is : " + test_str2)
# using naive method to
# Union Operation in two Strings
res = ""
temp = test_str1
for i in test_str2:
if i not in temp:
test_str1 += i
# printing result
print ("The string union is : " + test_str1)
Output : The original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string union is : GeeksforGeeksCda
Time Complexity: O(n*n), where n is the number of elements in the “test_str”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_str”.
Method 2 : Using set() + union() Set in python usually can perform the task of performing set operations such as set union. This utility of sets can be used to perform this task as well. Firstly, both the strings are converted into sets using set() and then union is performed using union(). Returns the sorted set.
Python3
# Python 3 code to demonstrate
# Union Operation in two Strings
# using set() + union()
# initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
# Printing initial strings
print ("The original string 1 is : " + test_str1)
print ("The original string 2 is : " + test_str2)
# using set() + union() to
# Union Operation in two Strings
res = set(test_str1).union(test_str2)
# printing result
print ("The string union is : " + str(res))
Output : The original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string union is : {'s', 'G', 'r', 'e', 'o', 'f', 'k', 'C', 'd', 'a'}
Method 3 : Using set() + | Another approach to perform the union operation on two strings could be using the | operator. The | operator returns a set that contains all elements from the first set and all elements from the second set that are not present in the first set.
Here is an example implementation:
Python3
# Python 3 code to demonstrate
# Union Operation in two Strings
# using | operator
# initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
# Printing initial strings
print ("The original string 1 is : " + test_str1)
print ("The original string 2 is : " + test_str2)
# using | operator to perform union
res = set(test_str1) | set(test_str2)
# printing result
print ("The string union is : " ,res)
OutputThe original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string union is : {'r', 'a', 'k', 'o', 's', 'G', 'd', 'e', 'C', 'f'}
The time complexity of this approach would be O(len(test_str1) + len(test_str2)) since we need to create sets from both strings and then perform the union operation on them. The space complexity would be O(len(res)) as the size of the result set would be equal to the number of unique characters in the union of the two strings.
Method 4 : Using reduce
In this method we first import the reduce function from functools. Then, we initialize two strings test_str1 and test_str2. We print the initial strings and then use reduce to perform the union operation. In the lambda function, we check if the character c is already present in the accumulated string acc. If it is not present, we append it to the accumulated string, otherwise we just return the accumulated string. We provide the initial accumulated string as test_str1 and the iterable as test_str2. Finally, we print the result of the union operation.
Python3
# Python3 code to demonstrate
# Union Operation in two Strings
# using reduce
from functools import reduce
# Initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
# Printing initial strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Using reduce to perform Union Operation on two strings
res = reduce(lambda acc, c: acc + c if c not in acc else acc, test_str2, test_str1)
# Printing the result
print("The string union is : " + res)
OutputThe original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string union is : GeeksforGeeksCda
Time Complexity: O(n*n), where n is the length of the concatenated string.
Auxiliary Space: O(n), where n is the number of elements in the “test_str”.
Similar Reads
Convert tuple to string in Python The goal is to convert the elements of a tuple into a single string, with each element joined by a specific separator, such as a space or no separator at all. For example, in the tuple ('Learn', 'Python', 'Programming'), we aim to convert it into the string "Learn Python Programming". Let's explore
2 min read
Python - Combine Strings to Matrix Sometimes while working with data, we can receive separate data in the form of strings and we need to compile them into Matrix for its further use. This can have applications in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split
4 min read
How to Append to String in Python ? In Python, Strings are immutable datatypes. So, appending to a string is nothing but string concatenation which means adding a string at the end of another string.Let us explore how we can append to a String with a simple example in Python.Pythons = "Geeks" + "ForGeeks" print(s)OutputGeeksForGeeks N
2 min read
Convert String to Tuple - Python When we want to break down a string into its individual characters and store each character as an element in a tuple, we can use the tuple() function directly on the string. Strings in Python are iterable, which means that when we pass a string to the tuple() function, it iterates over each characte
2 min read
Python | Add one string to another The concatenation of two strings has been discussed multiple times in various languages. But the task is how to add to a string in Python or append one string to another in Python. Example Input: 'GFG' + 'is best' Output: 'GFG is best' Explanation: Here we can add two string using "+" operator in Py
5 min read
String Interning in Python String interning is a memory optimization technique used in Python to enhance the efficiency of string handling. In Python, strings are immutable, meaning their values cannot be changed after creation. String interning, or interning strings, involves reusing existing string objects rather than creat
2 min read
Python Program to Convert a List to String In Python, converting a list to a string is a common operation. In this article, we will explore the several methods to convert a list into a string. The most common method to convert a list of strings into a single string is by using join() method. Let's take an example about how to do it.Using the
3 min read
Find the Union on List of Sets in Python The union of sets involves combining distinct elements from multiple sets into a single set, eliminating duplicates. In this article, we will study how to find the union on a list of sets in Python. Find the Union on a List of Sets in PythonBelow are some of the ways by which we can find the union o
4 min read
List of strings in Python A list of strings in Python stores multiple strings together. In this article, weâll explore how to create, modify and work with lists of strings using simple examples.Creating a List of StringsWe can use square brackets [] and separate each string with a comma to create a list of strings.Pythona =
2 min read
Python - Alternate Strings Concatenation The problem of getting the concatenation of a list is quite generic and we might someday face the issue of getting the concatenation of alternate elements and get the list of 2 elements containing the concatenation of alternate elements. Letâs discuss certain ways in which this can be performed. Met
3 min read