How to Sort a List of Numbers in Python

0 min read 108 words

The challenge

Finish the solution so that it sorts the passed-in array/list of numbers. If the function passes in an empty array/list or null/None value then it should return an empty array/list.

Examples:

solution([1,2,3,10,5]) # should return [1,2,3,5,10]
solution(None) # should return []

The solution in Python code

Option 1:

def solution(nums):
    if not nums:
        return []
    return sorted(nums)

Option 2:

def solution(nums):
    return sorted(nums) if nums else []

Option 3:

def solution(nums):
    return sorted(nums or [])

Test cases to validate our solution

import test
from solution import solution

@test.describe("Fixed Tests")
def fixed_tests():
    @test.it('Basic Test Cases')
    def basic_test_cases():
        test.assert_equals(solution([1,2,3,10,5]), [1,2,3,5,10])
        test.assert_equals(solution(None), [])
        test.assert_equals(solution([]), [])
        test.assert_equals(solution([20,2,10]), [2,10,20])
        test.assert_equals(solution([2,20,10]), [2,10,20])
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts