HackerRank Python (Basic) certification

Reverse Words Order and Swap Cases

Last checked 2 min read

A string question with two small steps. Most people who fail it do one of the steps on the wrong thing: they reverse the letters instead of the words.

What the question asks

You get a sentence made of words separated by single spaces. Return a new sentence with the same words in reverse order, and with the case of every letter flipped: lowercase becomes uppercase and uppercase becomes lowercase. The letters inside each word stay in their original order.

The constraints keep it simple: only English letters and spaces, the sentence starts and ends with a letter, no double spaces, at most 10 words of at most 10 letters each.

Function to write

reverse_words_order_and_swap_cases.pyPython 3
def reverse_words_order_and_swap_cases(sentence):
    # return a string
    ...

HackerRank reads the sentence from input, calls your function and writes the result. You only fill in the function body.

Solution

reverse_words_order_and_swap_cases.pyPython 3
def reverse_words_order_and_swap_cases(sentence):
    words = sentence.split(" ")
    words.reverse()
    return " ".join(words).swapcase()

How it works

  • split(" ") breaks the sentence into a list of words.
  • reverse() flips the order of that list in place. The words themselves are untouched.
  • " ".join(words) puts them back together with one space between each.
  • swapcase() flips the case of every letter in the joined string. Spaces are not affected.

The order does not matter here. Swapping case first and reversing later gives the same answer, because swapping case never moves a character.

Mistakes that fail the hidden tests

  • Reversing characters. sentence[::-1] or word[::-1] reverses letters, so “rUns dOg” becomes “GoD SNuR” instead of “DoG RuNS”.
  • A trailing space. Building the answer with result += word + " " leaves a space at the end. HackerRank compares the output exactly, so that line is wrong even though it looks right.
  • Swapping case by hand and missing a branch. Loops like if ch.islower(): ch.upper() without an else drop uppercase letters. str.swapcase() already does this correctly.
  • Printing instead of returning. The stub writes the returned value. A print inside the function gives an extra line and then None.

Try it on sample data

reverse_words_order_and_swap_cases.pyPython 3
print(reverse_words_order_and_swap_cases("aWESOME is cODING"))
print(reverse_words_order_and_swap_cases("rUns dOg"))

Output from my run:

Coding IS Awesome
DoG RuNS

For the first one: reversing the words gives “cODING is aWESOME”, and swapping the case gives “Coding IS Awesome”.