Reverse the words
Write reverse_words(s) that returns the words of s in reverse order, separated by single spaces. Extra spaces in the input should not matter.
reverse_words("one cs problem")
# "problem cs one"
reverse_words(" hello world ")
# "world hello"
Show hint
str.split() with no arguments splits on any run of whitespace and drops empty pieces.
Show solution
def reverse_words(s):
return " ".join(s.split()[::-1])
s.split() gives a clean list of words, [::-1] reverses it, and " ".join glues it back with single spaces. Runs in O(n) time.
Want a problem like this every day? See today's problem and keep a streak going.