Reversed Text
Source: May 2024, Task 3 (DTU 02002/02003). Study solution — not an official answer key.
Problem
Given a string of words separated by single spaces, and an option 'words' or 'letters':
'words'— reverse the order of the words'letters'— reverse the letters inside each word (keep word order)
Write reversed_text(text, option) returning the transformed string.
Example
>>> reversed_text('Hello world we are going to do some programming', 'letters')
'olleH dlrow ew era gniog ot od emos gnimmargorp'
Approach
Split on spaces. For words, reverse the list; for letters, reverse each word with slicing [::-1], then join with spaces.
Solution
Show solution Hide solution
Solution
def reversed_text(text, option):
words = text.split(" ")
if option == "words":
return " ".join(reversed(words))
if option == "letters":
return " ".join(word[::-1] for word in words)
raise ValueError("option must be 'words' or 'letters'")