Skip to content
ExamSpine

Lesson 5.10 · Write it

Reverse the words

A functionPython or Java9 tests, 4 of them hidden

On a phone? Put the lines in order instead

Write a function that returns a sentence with its words in reverse order.

  1. The words are separated by exactly one space, with no space at the start or the end. Words contain only letters, digits and punctuation.
  2. Punctuation stays with the word it is attached to, and each word keeps its capital letters.
  3. Empty text returns empty text.
  4. Put exactly one space between the words you return, and none at the start or the end.

Only the text your function returns is checked, exactly.

def reverse_words(sentence: str) -> str

Examples

Your function is tested on 9 cases: the 5 examples below, and 4 hidden ones that check the rules above.

  • reverse_words("the cat sat") should return "sat cat the": three words in reverse order
  • reverse_words("hello") should return "hello": one word stays as it is
  • reverse_words("Hi there, friend!") should return "friend! there, Hi": punctuation stays with its word (rule 2)
  • reverse_words("") should return "": empty text gives empty text (rule 3)
  • reverse_words("to be or not to be") should return "be to not or be to": the first word and the last word each appear twice

public static String reverseWords(String sentence)

Checking whether Java answers can run here.

Examples

Your function is tested on 9 cases: the 5 examples below, and 4 hidden ones that check the rules above.

  • reverseWords("the cat sat") should return "sat cat the": three words in reverse order
  • reverseWords("hello") should return "hello": one word stays as it is
  • reverseWords("Hi there, friend!") should return "friend! there, Hi": punctuation stays with its word (rule 2)
  • reverseWords("") should return "": empty text gives empty text (rule 3)
  • reverseWords("to be or not to be") should return "be to not or be to": the first word and the last word each appear twice
solution.pySolution.java