DEV Community

Galactic Circuit
Galactic Circuit

Posted on

Python Exercise of the Day: Reverse the Order of Words in a Sentence

Welcome to the Python Exercise of the Day, a series designed to help beginner programmers build confidence and skills through targeted coding challenges. Today, we focus on a string manipulation problem that sharpens your ability to work with Python’s core data structures and methods. This exercise is ideal for college students new to programming, offering a balance of simplicity and critical thinking. Let’s dive into the challenge, explore its significance, and invite you to enhance the solution.

The Challenge: Reverse Word Order

Your task is to write a Python function that accepts a string representing a sentence and returns a new string with the words in reverse order, while preserving the characters within each word. For example:

Input: "The quick brown fox"
Output: "fox brown quick The"

Constraints:

  • Words are separated by single spaces.
  • The input string contains no leading or trailing spaces.
  • The input is a valid string containing one or more words.

This problem tests your ability to manipulate strings and lists, fundamental skills in programming.


Why This Challenge Matters

String manipulation is a cornerstone of programming, appearing in tasks like text processing, data parsing, and user interface development. For beginners, this exercise introduces key Python methods and encourages logical problem decomposition. By solving this, you’ll practice splitting data, transforming it, and reassembling it—skills transferable to more complex projects like web scraping or natural language processing.


Think Before You Code

Before revealing the solution, consider how you might approach this problem. Break it into steps:

  • How can you split a sentence into individual words?
  • What technique would reverse the order of those words?
  • How do you combine the reversed words back into a sentence?

Take a moment to sketch a plan. This mental exercise builds problem-solving habits critical for programming.


Predict the Output

To engage with the problem, predict the output for these inputs:

  • "Python programming is fun"
  • "Hello"
  • "Data science rocks"

Write down your answers. We’ll verify them after the solution.


Visualizing the Process

To clarify the logic, imagine the process as a sequence:

Input: "The quick brown fox"
Step 1 (Split): ["The", "quick", "brown", "fox"]
Step 2 (Reverse): ["fox", "brown", "quick", "The"]
Step 3 (Join): "fox brown quick The"
Enter fullscreen mode Exit fullscreen mode

This mental model helps you understand the transformation at each stage.


The Solution

Here’s a Python function that reverses the word order:

def reverse_word_order(sentence):
    words = sentence.split()
    words.reverse()
    return " ".join(words)

# Test cases
print(reverse_word_order("The quick brown fox"))  # Output: fox brown quick The
print(reverse_word_order("Python programming is fun"))  # Output: fun is programming Python
print(reverse_word_order("Hello"))  # Output: Hello
Enter fullscreen mode Exit fullscreen mode

Explanation

The function operates in three steps:

  1. Splitting: The split() method, called without arguments, divides the string at each space, producing a list of words (e.g., "The quick brown fox" becomes ["The", "quick", "brown", "fox"]).
  2. Reversing: The reverse() method modifies the list in-place, rearranging elements from last to first (e.g., ["fox", "brown", "quick", "The"]).
  3. Joining: The join() method concatenates the list elements with a space separator, forming the final string (e.g., "fox brown quick The").

This approach is efficient, with a time complexity of O(n) where n is the string length, and readable for beginners.


Alternative Approach

For a more concise solution, consider this one-liner using list slicing:

def reverse_word_order_alt(sentence):
    return " ".join(sentence.split()[::-1])
Enter fullscreen mode Exit fullscreen mode

The slice [::-1] creates a reversed copy of the list. While elegant, it’s less explicit, so beginners may prefer the first version.


Common Pitfalls

Beginners often encounter these issues:

  • Missing Spaces: Using join() without a space (e.g., "".join(words)) concatenates words without separation (e.g., "foxbrownquickThe").
  • Modifying the Wrong Variable: Assigning words = words.reverse() sets words to None because reverse() returns None.
  • Assuming Non-String Inputs: The function may fail if given an integer or None.

Awareness of these errors helps you debug effectively.


Mini Quiz

Test your understanding:

What does " ".join(["a", "b", "c"]) return?
a) "abc"
b) "a b c"
c) ["a", "b", "c"]

What does sentence.split() do if sentence = "x y"?
a) ["x", "y"]
b) ["x", "", "", "y"]
c) ["x y"]

Answers: 1. b, 2. b. Review split() and join() if needed.


Challenge: Enhance the Function

Extend the solution with one or more of these modifications:

  • Error Handling: Raise a TypeError for non-string inputs and return an empty string for empty or whitespace-only inputs.
  • Multiple Spaces: Handle inputs with multiple consecutive spaces (e.g., "Hello World").
  • Custom Separator: Add a parameter to specify a separator (e.g., commas).
  • Manual Reverse: Reverse the list using a loop instead of reverse().

Example starter for error handling:

def reverse_word_order_safe(sentence):
    if not isinstance(sentence, str):
        raise TypeError("Input must be a string")
    if not sentence.strip():
        return ""
    words = sentence.split()
    words.reverse()
    return " ".join(words)
Enter fullscreen mode Exit fullscreen mode

Real-World Applications

This skill applies to:

  • Text Processing: Reordering words in log files or user inputs.
  • Natural Language Processing: Preprocessing text for chatbots or sentiment analysis.
  • Data Formatting: Rearranging fields in CSV files.

Learning this now prepares you for tools like Python’s re module or libraries like pandas.


Share Your Work

Take your solution to the next level by sharing it with the community! Implement one of the tweak challenges (e.g., error handling, custom separators) and post your code in the comments below or on X with the hashtag #PythonWordReverse. For an interactive experience, I’ve created a GitHub repository with a Codespace where you can run the challenge, experiment with the provided code, and submit your own solutions. Visit [https://github.com/GalacticCircuit/Daily-Python-Exercises] to get started—fork the repo, open a Codespace, and try the challenge in a ready-to-code environment. Add your solution as a new file (e.g., yourname_solution.py) and submit a pull request to showcase your work. Engaging with others’ solutions is a great way to learn new techniques and grow as a coder. _If you’re new to GitHub, the README includes step-by-step instructions to guide you.

_ What’s your favorite Python string trick? Share your thoughts and code to inspire others!


Next Steps

Try these related challenges:

  • Reverse the characters in each word (e.g., "Hello World" → "olleH dlroW").
  • Randomize word order using the random module.
  • Suggest your own challenge in the comments!

This exercise builds foundational skills and confidence.
What did you learn?
What topics (e.g., lists, dictionaries) would you like next?

Share your thoughts below to shape future posts.

Top comments (1)

Collapse
 
andriy_ovcharov_312ead391 profile image
Andriy Ovcharov

Interesting. Thanks for sharing!