Skip to content

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:

Input
sentence="apple banana orange", order=(0, 2, 1)
Output
"apple orange banana"
Input
sentence="cat dog mouse", order=(2, 1, 0)
Output
"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)

words = ["cat", "dog", "mouse"]
order:  2→"mouse",  1→"dog",  0→"cat"
→ "mouse dog cat" ✓


Solution approaches

def shuffle_sentence(sentence, order):
    words = sentence.split()
    return " ".join(words[i] for i in order)
def shuffle_sentence(sentence, order):
    words   = sentence.split()
    result  = []
    for i in order:
        result.append(words[i])
    return " ".join(result)
def shuffle_sentence(sentence, order):
    words = sentence.split()
    return " ".join([words[i] for i in order])
from operator import itemgetter

def shuffle_sentence(sentence, order):
    words = sentence.split()
    return " ".join(itemgetter(*order)(words))

itemgetter(*order)(words) selects multiple items from words by their indices in one call - returns a tuple of the selected words.

shuffle_sentence = lambda sentence, order: " ".join(
    sentence.split()[i] for i in order
)

Key takeaways

01

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.

02

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.

03

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.