Logic Building
def reverse_words(words, index=0):
# Base case
if index >= len(words):
return ""
# Recurse first
result = reverse_words(words, index + 1)
# Add current word
if result:
return result + " " + words[index]
else:
return words[index]
# Test
text = input("Enter a string: ")
words = text.split()
result = reverse_words(words)
print(f"Reversed words: {result}")Output
Enter a string: Hello World Programming Reversed words: Programming World Hello
Recurse first, then add current word.
Key Concepts:
- Split into words
- Recurse before adding word
- Creates reverse order