Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 9

Sort a list of numbers ascending and descending

Easy

10 minute session

Summary

Return a sorted copy of a list of numbers in ascending or descending order.

Problem statement

Write a function sort_numbers(nums, reverse=False) that takes a list of numbers (ints and/or floats) and returns a new list sorted in ascending order when reverse is False, or in descending order when reverse is True. Do not mutate the original list.

Task

Implement a function to return a new list sorted in ascending order by default or descending when requested.

Examples

Ascending sort (default)

Input

sort_numbers([3, 1, 2])

Output

[1, 2, 3]

Explanation

Default returns numbers sorted ascending.

Input format

A list of numbers and an optional boolean reverse flag.

Output format

A new list of numbers sorted in the requested order.

Constraints

Should handle empty lists and a mix of ints and floats. Aim for O(n log n) time using Python's sorting facilities.

Samples

Sample input 0

sort_numbers([3, 1, 2], True)

Sample output 0

[3, 2, 1]

Explanation 0

reverse=True returns numbers sorted descending.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

09:09 PM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.