S1Q2 · Shuffle a Three-Word Sentence¶
⚡ Quick Reference
Function: shuffle_sentence(sentence: str, order: tuple) -> str
Core idea: split into words, pick them in the order given by the tuple, rejoin with spaces.
def shuffle_sentence(sentence, order):
words = sentence.split()
return " ".join(words[i] for i in order)
Key rules:
- order contains 0-based indices into the word list
- Pick words in the sequence given by order
- Rejoin with a single space
Problem Statement¶
Problem
Write a function shuffle_sentence(sentence, order) that rearranges the three words of a sentence according to the index tuple order.
Examples:
sentence="apple banana orange", order=(0, 2, 1)
"apple orange banana"
sentence="cat dog mouse", order=(2, 1, 0)
"mouse dog cat"
Tracing both examples¶
Example 1: "apple banana orange", order (0, 2, 1)
words = ["apple", "banana", "orange"]
order: 0→"apple", 2→"orange", 1→"banana"
→ "apple orange banana" ✓
Example 2: "cat dog mouse", order (2, 1, 0)
Solution approaches¶
Key takeaways¶
split() + join() - the standard word-shuffle pattern
sentence.split() breaks the sentence into a list of words. Indexing by the order tuple selects them in the new arrangement. " ".join() reassembles them into a string.
Order is 0-based
The order tuple uses 0-based indices - 0 = first word, 1 = second, 2 = third. No subtraction needed since Python list indexing is already 0-based.
Works for any number of words, not just three
Although the problem specifies three words, the solution " ".join(words[i] for i in order) generalises to any sentence length - the order tuple drives everything.