Python-algos: Sentence Reversal

Avitosh Totaram
1 min readApr 6, 2020

Given a string of words, reverse all the words. For example:

“Hi my name is Avi”, becomes “Avi is name my Hi”.

def rev_word3(s):

words = []
length = len(s)
spaces = [' ']
i = 0
while i < length:
if s[i] not in spaces:
word_start = i

while i < length and s[i] not in spaces:
i += 1
words.append(s[word_start:i])
i += 1
return " ".join(reversed(words))

The code above makes an empty array of words, finds the length of the input, an array with a space and an index start point. The code checks for the index being shorter than the length of the input in the first loop. The second loop checks for the final letter index of the word, then it returns the words reversed.

--

--

Avitosh Totaram

Problem solver with experience in Software, and Mechanical engineering. Interested in web-dev, machine learning, artificial intelligence, and new technologies.