Problem 6.4

Reverse Words

Write a function reverse_words that takes a sentence and returns a new sentence with all the words in the reserse order.

>>> reverse_words("joy of programming")
'programming of joy'

>>> reverse_words("less is more")
'more is less'

>>> reverse_words("road goes ever on and on")
'on and on ever goes road'

Please note that only the order of the words in the sentence is reversed, not the letters in each word.

Solution

def reverse_words(sentence):
    words = sentence.split()
    return " ".join(words[::-1])