Python – All possible space joins in String
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
test_str = 'Geeksforgeeks is best for geeks'
print ( "The original string is : " + str (test_str))
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)
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
import itertools
test_str = 'Geeksforgeeks is best for geeks'
print ( "The original string is : " + str (test_str))
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)
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
def all_possible_spaces(s, i):
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 :]
for sub in all_possible_spaces(right, i + 1 ):
result.append(left + ' ' + sub)
return result
s = 'Geeksforgeeks is best for geeks'
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
test_str = 'Geeksforgeeks is best for geeks'
print ( "The original string is : " + str (test_str))
words = test_str.split()
res = [ ' ' .join(combo) for i in range ( 1 , len (words) + 1 )
for combo in itertools.product(words, repeat = i)]
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
test_str = 'Geeksforgeeks is best for geeks'
words = test_str.split()
res = [f "{' '.join(words[:i])} {' '.join(words[i:])}" for i in range (
1 , len (words))]
print ( "The original string is : " + str (test_str))
print ( "All possible spaces List : " + str (res))
|
Output
All 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.
Last Updated :
08 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...