Python - All possible space joins in String
Last Updated :
08 May, 2023
Sometimes, while working with Python Strings, we can have a problem in which we need to construct strings with a single space at every possible word ending. This kind of application can occur in domains in which we need to perform testing. Let us discuss certain ways in which this task can be performed.
Method #1: Using loop + join()
This is a brute-force way in which this task can be performed. In this, we perform the task of forming all possible joins using join() and the task of iterating through all strings using a loop.
Python3
# Python3 code to demonstrate working of
# All possible space joins in String
# Using loop + join()
# Initializing string
test_str = 'Geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# All possible space joins in String
# Using loop + join()
res = []
temp = test_str.split(' ')
strt_idx = 0
lst_idx = len(temp)
for idx in range(len(temp)-1):
frst_wrd = "".join(temp[strt_idx: idx + 1])
scnd_wrd = "".join(temp[idx + 1: lst_idx])
res.append(frst_wrd + " " + scnd_wrd)
# Printing result
print("All possible spaces List : " + str(res))
Output :
The original string is : Geeksforgeeks is best for geeks All possible spaces List : ['Geeksforgeeks isbestforgeeks', 'Geeksforgeeksis bestforgeeks', 'Geeksforgeeksisbest forgeeks', 'Geeksforgeeksisbestfor geeks']
Time Complexity: O(n2) -> (loop + join)
Auxiliary Space: O(n)
Method #2: Using enumerate() + join() + combinations()
A combination of the above methods can be used to perform this task. In this, we perform the task of extracting combinations using combinations(). This prints all combinations of all occurrences of spaces rather than just one as in the above method.
Python3
# Python3 code to demonstrate working of
# All possible space joins in String
# Using enumerate() + join() + combinations()
import itertools
# initializing string
test_str = 'Geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# All possible space joins in String
# Using enumerate() + join() + combinations()
res = []
temp = test_str.split(' ')
N = range(len(temp) - 1)
for idx in N:
for sub in itertools.combinations(N, idx + 1):
temp1 = [val + " " if i in sub else val for i, val in enumerate(temp)]
temp2 = "".join(temp1)
res.append(temp2)
# Printing result
print("All possible spaces List : " + str(res))
Output :
The original string is : Geeksforgeeks is best for geeks All possible spaces List : ['Geeksforgeeks isbestforgeeks', 'Geeksforgeeksis bestforgeeks', 'Geeksforgeeksisbest forgeeks', 'Geeksforgeeksisbestfor geeks', 'Geeksforgeeks is bestforgeeks', 'Geeksforgeeks isbest forgeeks', 'Geeksforgeeks isbestfor geeks', 'Geeksforgeeksis best forgeeks', 'Geeksforgeeksis bestfor geeks', 'Geeksforgeeksisbest for geeks', 'Geeksforgeeks is best forgeeks', 'Geeksforgeeks is bestfor geeks', 'Geeksforgeeks isbest for geeks', 'Geeksforgeeksis best for geeks', 'Geeksforgeeks is best for geeks']
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method#3: Recursive approach
Steps:
- Define a recursive function named all_possible_spaces that takes a string s and a current index i as input.
- If i is equal to the length of s, return an empty list.
- If i is equal to the last index of s, return a list containing s as the only element.
- Define a list named result.
- For each index j greater than or equal to i and less than the length of s:
- Define a variable named left as s from i to j and a variable right as s from j+1 to the end.
- Recursively call the all_possible_spaces to function on right with the current index as i+1.
- For each element in the list returned by the recursive call, append left + ' ' + element to the result list.
- Return the result list.
- Call the all_possible_spaces() function on the input string with an initial index of 0.
Python3
# Python program for the above approach
# Function to find the list of all possible
# spaces in the string
def all_possible_spaces(s, i):
# Base Case
if i == len(s):
return []
if i == len(s)-1:
return [s]
result = []
for j in range(i, len(s)):
left = s[i:j+1]
right = s[j+1:]
# Recursive Call
for sub in all_possible_spaces(right, i+1):
result.append(left + ' ' + sub)
return result
# Driver Code
s = 'Geeksforgeeks is best for geeks'
# Printing possible space in list
print('All possible spaces List :', all_possible_spaces(s, 0))
Output...g eeks', 'Geeksforgeeks is est f g eeks', 'Geeksforgeeks is est fo g eeks', 'Geeksforgeeks is est for ge eks', 'Geeksforgeeks is b s for g eeks', 'Geeksforgeeks is b st or g eeks', 'Geeksforgeeks is b st r g eeks', 'Geeksforgeeks is b st f g eeks', 'Geeksforgeeks is b st fo g eeks', 'Geeksforgeeks is b st for ge eks', 'Geeksforgeeks is be t or g eeks', 'Geeksforgeeks is be t r g eeks', 'Geeksforgeeks is be t f g eeks', 'Geeksforgeeks is be t fo g eeks', 'Geeksforgeeks is be t for ge eks', 'Geeksforgeeks is bes r g eeks', 'Geeksforgeeks is bes f g eeks', 'Geeksforgeeks is bes fo g eeks', 'Geeksforgeeks is bes for ge eks', 'Geeksforgeeks is best f g eeks', 'Geeksforgeeks is best fo g eeks', 'Geeksforgeeks is best for ge eks', 'Geeksforgeeks is best o g eeks', 'Geeksforgeeks is best or ge eks', 'Geeksforgeeks is best f r ge eks', 'Geeksforgeeks is best fo ge eks', 'Geeksforgeeks is best for ge eks', 'Geeksforgeeks is best for e eks', 'Geeksforgeeks is best for gee ks']
Time Complexity: O(2n), where n is the number of spaces in the input string. This is the worst-case time complexity when all possible combinations of spaces are considered.
Auxiliary Space: O(2n), where n is the number of spaces in the input string. This is the worst-case space complexity when all possible combinations of spaces are considered.
Method #5: Using itertools.product()
In this approach, we use itertools.product() function to generate all possible combinations of words in the input string. We then join each combination using a space and add it to a list, which is returned as the output.
Python3
import itertools
# initializing string
test_str = 'Geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# All possible space joins in String
# Using itertools.product()
words = test_str.split()
res = [' '.join(combo) for i in range(1, len(words)+1)
for combo in itertools.product(words, repeat=i)]
# printing result
print("All possible spaces List : " + str(res))
Output...eeks geeks for geeks Geeksforgeeks', 'geeks geeks for geeks is', 'geeks geeks for geeks best', 'geeks geeks for geeks for', 'geeks geeks for geeks geeks', 'geeks geeks geeks Geeksforgeeks Geeksforgeeks', 'geeks geeks geeks Geeksforgeeks is', 'geeks geeks geeks Geeksforgeeks best', 'geeks geeks geeks Geeksforgeeks for', 'geeks geeks geeks Geeksforgeeks geeks', 'geeks geeks geeks is Geeksforgeeks', 'geeks geeks geeks is is', 'geeks geeks geeks is best', 'geeks geeks geeks is for', 'geeks geeks geeks is geeks', 'geeks geeks geeks best Geeksforgeeks', 'geeks geeks geeks best is', 'geeks geeks geeks best best', 'geeks geeks geeks best for', 'geeks geeks geeks best geeks', 'geeks geeks geeks for Geeksforgeeks', 'geeks geeks geeks for is', 'geeks geeks geeks for best', 'geeks geeks geeks for for', 'geeks geeks geeks for geeks', 'geeks geeks geeks geeks Geeksforgeeks', 'geeks geeks geeks geeks is', 'geeks geeks geeks geeks best', 'geeks geeks geeks geeks for', 'geeks geeks geeks geeks geeks']
Time complexity: O(2^n), where n is the number of words in the input string.
Auxiliary space: O(2^n), since we store all possible combinations in a list.
Method#5 Using list comprehension and slicing
Approach:
- Initialize the input string test_str.
- Split the input string into words and store the words in a list of words.
- Initialize an empty list res to store all possible space joins of the words in words.
- Iterate through all possible split points i of the words in words using a range function.
- Generate a space join of the first i words and the remaining words after i.
- Append the generated space join to the list res.
- Print the original input string and the list of all possible space joins.
Python3
# Initializing input list
test_str = 'Geeksforgeeks is best for geeks'
# split string into words
words = test_str.split()
# Generating all possible space joins
res = [f"{' '.join(words[:i])} {' '.join(words[i:])}" for i in range(
1, len(words))]
# Print original string
print("The original string is : " + str(test_str))
# Print result
print("All possible spaces List : " + str(res))
OutputAll possible spaces List : ['Geeksforgeeks is best for geeks', 'Geeksforgeeks is best for geeks', 'Geeksforgeeks is best for geeks', 'Geeksforgeeks is best for geeks']
Time complexity: O(n^2), where n is the number of words in the input string. This is because the program needs to iterate through all possible split points of the words and generate a space join for each split point.
Auxiliary space: O(n^2), where n is the number of words in the input string. This is because the program needs to store all possible space joins in the list res.
Similar Reads
Python - Avoid Spaces in string length When working with strings in Python, we may sometimes need to calculate the length of a string excluding spaces. The presence of spaces can skew the length when we're only interested in the number of non-space characters. Let's explore different methods to find the length of a string while ignoring
3 min read
Split and join a string in Python The goal here is to split a string into smaller parts based on a delimiter and then join those parts back together with a different delimiter. For example, given the string "Hello, how are you?", you might want to split it by spaces to get a list of individual words and then join them back together
3 min read
Join Elements of a Set into a String in Python You might have encountered situations where you needed to join the elements of a set into a string by concatenating them, which are separated by a particular string separator. Let's say we want to convert the set {"GFG", "courses", "are", "best"} into a string with a space between each element that
4 min read
Test if String Contains Alphabets and Spaces - Python We are given a string and the task is to determine whether it contains only alphabets and spaces, this is often required when working with datasets where the string must not include any digits, punctuation or special characters.Using all() isspace() and isalpha()This method iterates through each cha
3 min read
Python - Check for spaces in string Sometimes, while working with strings in Python, we need to determine if a string contains any spaces. This is a simple problem where we need to check for the presence of space characters within the string. Let's discuss different methods to solve this problem.Using 'in' operator'in' operator is one
3 min read