Easy: Warm-Ups · Problem 5 of 82

Reverse the Words

EasyStringsPython

Write reverse_words(sentence) that returns the words of the sentence in reverse order, separated by single spaces. The input may have extra spaces at the start, at the end or between words; the output must not.

" the sky is blue " becomes "blue is sky the".

Understand the problem

Look at what the two kinds of split give.

What does "a b".split(" ") return? (There are two spaces between a and b.)

  1. ["a", "b"]
  2. ["a", "", "b"]
  3. ["a b"]

Splitting on a single space cuts at every space, and two spaces in a row leave an empty string between them.

What does " a b ".split() return, with no argument?

  1. ["a", "b"]
  2. ["", "a", "", "b", ""]

split() with no argument splits on runs of whitespace and ignores whitespace at both ends. It never gives empty strings.

What does " ".join(["x", "y"]) return? Type it without quotes.

join glues the items together with the string it is called on between them: "x y".

Write the solution

Return one string. The tests include empty text and only spaces.

def reverse_words(sentence):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

Which tool cuts the sentence into words and ignores the extra spaces for you?

Hint 2: the shape of the answer

Split into a list of words, reverse the list, and join with one space.

Reflect

Solution

def reverse_words(sentence):
    return " ".join(reversed(sentence.split()))

Another way: slice with a negative step

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

What this tests: split() versus split(" "), join, reversed and slicing.

Reverse the words, not the letters. sentence[::-1] reverses every character, so "blue is" would become "si eulb". Read the task twice before you pick the tool.

Cost: O(n) time and space. reversed() makes an iterator, [::-1] makes a copy; for words the difference is tiny.

What an interviewer might ask next: Now reverse the letters of every word but keep the word order. (" ".join(w[::-1] for w in s.split()).)