Reverse String Words Recursively
Reverse word order with a recursive list helper. Students split whitespace, build the suffix result first, and join words without reversing letters inside them.
1def reverse_words(words, index=0):2 # Base case3 if index >= len(words):4 return ""56 # Recurse first7 result = reverse_words(words, index + 1)8 # Add current word9 if result:10 return result + " " + words[index]11 else:12 return words[index]1314# Test15text = input("Enter a string: ")16words = text.split()17result = reverse_words(words)18print(f"Reversed words: {result}")
Output
Enter a string: Hello World Programming Reversed words: Programming World Hello
In this one
- Choose words as the unit
- Reverse through suffix returns
- Control join separators
How it works
- 1
Split input into whitespace-delimited words.
- 2
Recursively build the later words first.
- 3
Append the current word with a separator only if needed.
Edge cases
What if the input is only spaces?
What if the input is only spaces?
split gives an empty list and the result is empty.
Are letters inside each word reversed?
Are letters inside each word reversed?
No. Only the order of whole words changes.
What's going on
split creates the words before recursion begins. The helper processes later words first, then adds the current word after that returned result.
The empty suffix needs special handling to avoid a leading separator. For red blue green, the result is green blue red. Character order inside each word stays unchanged. split without arguments collapses whitespace, so original spacing is not preserved.
What if the input is only spaces? split gives an empty list and the result is empty.
Are letters inside each word reversed? No. Only the order of whole words changes.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why check if result is nonempty?
Pick an answer to check it.
Question 2
What if the input is only spaces?
Pick an answer to check it.
Questions people ask
What if the input is only spaces?
split gives an empty list and the result is empty.
Are letters inside each word reversed?
No. Only the order of whole words changes.
Why check if result is nonempty?
To avoid an unwanted separator at the start.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum