Reverse String Words Recursively

Reverse order of words in string recursively.

AdvancedPhase 3 - Level 4: String-based RecursionExample 10 of 10
reverse-string-words-recursively.py
1def reverse_words(words, index=0):
2 # Base case
3 if index >= len(words):
4 return ""
5
6 # Recurse first
7 result = reverse_words(words, index + 1)
8 # Add current word
9 if result:
10 return result + " " + words[index]
11 else:
12 return words[index]
13
14# Test
15text = 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

What's going on

Recurse first, then add current word.

Key Concepts:

Split into words
Recurse before adding word
Creates reverse order