Python code for reverse:
Reverse from:
['row row row your boat',
'gently down the stream.',
'happily happily happily happily',
'life is but a dream' ],
Output should be:
['boat your row row row',
'stream the down gently.',
'happily happily happily happily',
'dream a but is life']
How can I achieve this?
Code Explanation-
Given a list containing strings ,we have to reverse the strings with out changing the original words of the string.
We can do it by using reversed() method in python but in the given input it contains characters such as ',' and it is not interchanged i.e it is in same place evn after the reversing the string ,inorder to handle these cases we are using regular expressions and finding if there is a character such as '.' if the character is there we do not move it we place it in the same original place and reverse the other words in the string ,not only '.' it ma contain characters such as , ?; like these we will handle these cases too.
Note- This program needs regular expressions to handle '.' and other characters such as ?;,
Below is the code with clear comments and explanation-
#importing regular expression to acheive the testcases such as .,?
import re
#r'([,:;?!.]+)$'
#our function to reverse words in a given list of strings
def myreverse(listinput):
#creating a string of ,:?!. to handle these in the strings
handlingother= ',:;?!.'
#creating a empty list to return the result
z=[]
#iterating through the list of strings
for i in range(len(listinput)):
#checking if each string in the list has .,:?!.
checkother=re.search(r'([,:;?!.]+)$',listinput[i])
#if the value of checkother is none means if the string does'nt contain any character like .?!;
#we keep it as empty string and store in a variable called finalvalue
if(checkother is None):
finalvalue=''
#if the value of checkother is not none
else:
#the group method returns the characters which match the character such as ,?. in the string
#and store in the variable finalvalue
finalvalue=checkother.group(True)
#creating a variable which stores our reversed string result
#we are using rstrip method to remove character such as .,? by finding the characters like .,? using
#findall method as a regular expression and reversing the whole string and appending with spaces using join
#method and at last concatenating the finalvalue at end using + symbol
new= ' '.join(reversed(re.findall(r'[\w,:;?!.]+',listinput[i].rstrip(handlingother))))+finalvalue
#appending the result to a list called z
z.append(new)
#returning oyr result
return z
#our input
listinput=['row row row your boat',
'gently down the stream.',
'happily happily happily happily',
'life is but a dream']
#callling our function myreverse by passing a parameter listinput which contains our input as per the question.
print(myreverse(listinput))
Code with output screens-
(Hope you like the work if you have any doubt please comment I will Defininately help you.)
Get Answers For Free
Most questions answered within 1 hours.