Python Program to reverses alternate strings and then concatenates all elements
Last Updated :
28 Feb, 2023
Given a String List of length N, the following program returns a concatenated list of all its string elements with its alternate elements reversed.
Input: test_str = 'geeksgeeks best for geeks'
Output: skeegskeeg best rof geeks
Explanation: Alternate words reversed.
Input: test_str = 'geeksgeeks best geeks'
Output: skeegskeeg best skeeg
Explanation: Alternate words reversed.
Method 1: Using reversed() and loop
In this, perform the task of reversing strings using reversed() and then check for alternates using the % operator and concatenate accordingly.
Python3
# initializing string
test_str = 'geeksgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# splitting string
temp = test_str.split()
res = []
for idx in range(len(temp)):
# reversing if alternate
if idx % 2 == 0:
res.append(''.join(list(reversed(temp[idx]))))
else :
res.append(temp[idx])
res = ' '.join(res)
# printing result
print("Transformed String : " + str(res))
OutputThe original string is : geeksgeeks is best for geeks
Transformed String : skeegskeeg is tseb for skeeg
Time Complexity: O(N) , a single for loop takes O(N) time complexity
Auxiliary Space: O(N)
Method 2 : Using slicing and list comprehension
In this, we perform task of reversal using slicing and then list comprehension is used to perform the task done by loop, in shorthand.
Python3
# initializing string
test_str = 'geeksgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# splitting string
temp = test_str.split()
# list comprehension to solve problem in 1 liner
res = ' '.join([''.join(list(reversed(temp[idx]))) if idx % 2 == 0 else temp[idx] for idx in range(len(temp))])
# printing result
print("Transformed String : " + str(res))
OutputThe original string is : geeksgeeks is best for geeks
Transformed String : skeegskeeg is tseb for skeeg
Time Complexity: O(N)
Auxiliary Space: O(N)
Method 3: Using list comprehension and enumerate
Algorithm for reversing alternate strings and then concatenating all elements using list comprehension and enumerate approach:
Input:
A string test_str
Output:
A transformed string res, which reverses alternate strings and then concatenates all elements
Steps:
Split the given string test_str into a list of words using the split() function, and assign the resulting list to a temporary variable temp.
Iterate over the list of words using enumerate() and list comprehension.
For each word, check if its index (obtained from enumerate) is even or odd. If it's even, reverse the word using the reversed() function and join the characters to form a new string.
If the index is odd, simply keep the word as it is.
Join the resulting list of words using the join() function, with a space character as the separator.
Assign the resulting string to a variable res and return it as the final output.
Python3
# initializing string
test_str = 'geeksgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# splitting string
temp = test_str.split()
# using enumerate and list comprehension to solve problem
res = ' '.join([(''.join(list(reversed(word))) if idx % 2 == 0 else word) for idx, word in enumerate(temp)])
# printing result
print("Transformed String : " + str(res))
OutputThe original string is : geeksgeeks is best for geeks
Transformed String : skeegskeeg is tseb for skeeg
Time Complexity:
The algorithm uses a single loop and a list comprehension to iterate over the list of words and reverse alternate strings. Thus, the time complexity of the algorithm is O(n), where n is the number of words in the input string.
Auxiliary Space Complexity:
The algorithm uses two variables: temp to store the list of words and res to store the transformed string. The space complexity of these variables is O(n) since they depend on the size of the input string. However, the list comprehension uses temporary variables for each reversed string, so the space complexity is also proportional to the length of the longest string in the input. Therefore, the auxiliary space complexity of the algorithm is O(n + m), where n is the number of words in the input string and m is the length of the longest word in the input.
Method 4: Using map function and lambda function:
Algorithm:
1.Initialize the input string test_str with the value 'geeksgeeks is best for geeks'
2.Split the input string into a list of individual words using whitespace as the delimiter and store it in the words variable.
3.Use the map function along with a lambda function to transform each element of the list.
4.If the index is even, reverse the characters of the corresponding word and return it.
5.If the index is odd, return the word as is.
6.Join the resulting list of transformed words into a string using a space as the separator and store it in the res variable.
7.Print the transformed string.
Python3
# Initialize the string to be transformed
test_str = 'geeksgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# Split the string into individual words using whitespace as the delimiter
words = test_str.split()
# Use map to apply a function to each element of the range object and join the resulting sequence into a string
# The lambda function takes an index i and checks whether it is even. If it is, it reverses the characters of the corresponding word and returns it; otherwise, it returns the word as-is.
res = ' '.join(map(lambda i: ''.join(list(reversed(words[i]))) if i % 2 == 0 else words[i], range(len(words))))
# Print the transformed string
print(res)
#This code is contributed by Jyothi pinjala.
OutputThe original string is : geeksgeeks is best for geeks
skeegskeeg is tseb for skeeg
Time complexity:
The time complexity of the given code is O(nm), where n is the number of words in the input string and m is the length of the longest word. This is because the code needs to iterate over each word in the input string and reverse the characters of every other word. The join function also takes O(n) time to concatenate the transformed words back into a string.
Auxiliary Space:
The space complexity of the given code is O(nm), where n is the number of words in the input string and m is the length of the longest word. This is because the code needs to store each word as a separate string in the list words, and also needs to create a new reversed string for every other word in the list. The resulting transformed string also takes O(nm) space to store.
Similar Reads
Python program to reverse the content of a file and store it in another file
Given a text file. The task is to reverse as well as stores the content from an input file to an output file. This reversing can be performed in two types.  Full reversing: In this type of reversing all the content gets reversed.  Word to word reversing: In this kind of reversing the last word comes
2 min read
Python program to concatenate Strings around K
Given List of Strings, join all the strings which occurs around string K. Input : test_list = ["Gfg", "*", "is", "best", "*", "love", "gfg"], K = "*" Output : ['Gfg*is', 'best*love', 'gfg'] Explanation : All elements around * are joined.Input : test_list = ["Gfg", "$", "is", "best", "$", "love", "gf
5 min read
Reverse Alternate Characters in a String - Python
Reversing alternate characters in a string involves rearranging the characters so that every second character is reversed while maintaining the original order of other characters. For example, given the string 'abcde', reversing the alternate characters results in 'ebcda', where the first, third and
3 min read
Python program to count the pairs of reverse strings
Given the String list, write a Python program to count pairs of reverse strings. Examples: Input : test_list = ["geeks", "best", "tseb", "for", "skeeg"] Output : 2 Explanation : geeks, skeeg and best, tseb are 2 pairs of reverse strings available. Input : test_list = ["geeks", "best", "for", "skeeg"
6 min read
Python program to Reverse a single line of a text file
Given a text file. The task is to reverse a single line of user's choice from a given text file and update the already existing file. Examples: Input: Hello Geeks for geeks! User choice = 1 Output: Hello Geeks geeks! for Input: This is a geek Welcome to GeeksforGeeks GeeksforGeeks is a computer scie
2 min read
Python Program to Reverse the Content of a File using Stack
Given a file, the task is to change the content in reverse order using Stack, as well as store the lines of that file in reverse order in Python. Examples: Input: 1 2 3 4 5 Output: 5 4 3 2 1 Approach to Python Program to Reverse a Stack Using Recursion Create an empty stack. One by one push every l
2 min read
Python program to print k characters then skip k characters in a string
Given a String, extract K characters alternatively. Input : test_str = 'geeksgeeksisbestforgeeks', K = 4 Output : geekksisforg Explanation : Every 4th alternate range is sliced. Input : test_str = 'geeksgeeksisbest', K = 4 Output : geekksis Explanation : Every 4th alternate range is sliced. Method #
5 min read
Python program to remove last N characters from a string
In this article, weâll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions.Using String SlicingString slicing is one of the simplest and mos
2 min read
Concatenate all Elements of a List into a String - Python
We are given a list of words and our task is to concatenate all the elements into a single string with spaces in between. For example, given the list: li = ['hello', 'geek', 'have', 'a', 'geeky', 'day'] after concatenation, the result will be: "hello geek have a geeky day".Using str.join()str.join()
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