I am trying to reverse a word in a sentence.
for example:
arr = [ 'p', 'e', 'r', 'f', 'e', 'c', 't', ' ', 'm', 'a', 'k', 'e', 's', ' ', 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e' ]
should be
[ 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ', 'm', 'a', 'k', 'e', 's', ' ', 'p', 'e', 'r', 'f', 'e', 'c', 't' ]
I wrote the following code, which reverse the whole array then reverse each word
def reverse_words(arr):
def mirrorReverse(arr,start,end):
while(start<end):
tmp=arr[start]
arr[start]=arr[end]
arr[end]=tmp
start+=1
end-=1
n=len(arr)
mirrorReverse(arr,0,n-1)
for i in range(len(arr)):
if arr[i]==' ' and start==0: #first word
mirrorReverse(arr,start,i-1)
start=i+1
elif i==len(arr)-1: #last word
mirrorReverse(arr,start,i)
elif arr[i]==' ' and start!=None: #middle
mirrorReverse(arr,start,i-1)
start=i+1
return arr
this works fine and outputs the required answer however when I use a different example it doesn't work:
test 1:
["a"," "," ","b"]
Expected:
["b"," "," ","a"]
Actual:
['a', ' ', ' ', 'b']
test2:
["y","o","u"," ","w","i","t","h"," ","b","e"," ","f","o","r","c","e"," ","t","h","e"," ","m","a","y"]
output:
['y', 'o', 'u', ' ', 'w', 'i', 't', 'h', ' ', 'b', 'e', ' ', 'f', 'o', 'r', 'c', 'e', ' ', 't', 'h', 'e', ' ', 'm', 'a', 'y']
even though test2 is similar to the main example above which worked perfectly fine. Any help
Your code looks okay. You have double white spaces in your example and code.Test cases however have single white space. When I copy paste your code and change double white spaces inside if's to single white space everything works.