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.
- The words are separated by exactly one space, with no space at the start or the end. Words contain only letters, digits and punctuation.
- Punctuation stays with the word it is attached to, and each word keeps its capital letters.
- Empty text returns empty text.
- 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)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.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