Reputation: 720
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
Upvotes: 1
Views: 462
Reputation: 21
Here is one way of reversing a sentence and then joining:
sentence = "perfect makes practice"
s_list = sentence.split(" ")
s_list.reverse()
print(" ".join(s_list))
Upvotes: 1
Reputation: 755
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.
Upvotes: 1
Reputation: 3856
Please try the following solution for your concrete case:
if __name__ == "__main__":
x = ['p', 'e', 'r', 'f', 'e', 'c', 't', '', 'm', 'a', 'k', 'e', 's', '', 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e']
words = []
word = ""
for letter in x:
if len(letter) == 1:
word += letter
else:
words.append(word)
word = ""
words.append(word) # add the last one
result = []
for w in words[::-1]:
for letter in w:
result.append(letter)
result.append("")
result.pop() # remove the last one ""
print(result)
Upvotes: 1
Reputation: 58666
Firstly, at the Python prompt:
>>> def revwords(str):
... list = str.split()
... list.reverse()
... return ' '.join(list)
...
>>> revwords('The quick brown fox jumped over the lazy dogs.')
'dogs. lazy the over jumped fox brown quick The'
We can use the above with the array-of-characters representation that is required, by doing some recombining and splitting. Continuing at the Python prompt:
>>> list(revwords(''.join(['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'])))
['w', 'o', 'r', 'l', 'd', ' ', 'H', 'e', 'l', 'l', 'o']
Upvotes: 2