Squares of a Sorted List (via Leetcode)¶
Date published: 2020-04-12
Category: Python
Subcategory: Beginner Algorithms
Tags: functions, loops, lists
This problem can be found on Leetcode.
Problem statement:
Given a list of integers in non-decreasing order, return a list of the squares of each number in ascending order.
Test Cases¶
In [10]:
Copied!
# assert sorted_squares([-2, 0, 3]) == [0, 4, 9]
# assert sorted_squares([-2, 0, 3]) == [0, 4, 9]
The squares of [-2, 0, 3]
are [4, 0, 9]
. Sorted this list is [0, 4, 9]
.
In [11]:
Copied!
# assert sorted_squares([-3, 1, 9]) == [1, 9, 81 ]
# assert sorted_squares([-3, 1, 9]) == [1, 9, 81 ]
The squares of [-3, 1, 9]
are [9, 1, 81]
. Sorted this list is [1, 9, 81]
.
Pseudocode¶
In [12]:
Copied!
# define a function that takes in an input list:
# create a new list that's the square of each number
# sort the list of squares
# return list of squares
# define a function that takes in an input list:
# create a new list that's the square of each number
# sort the list of squares
# return list of squares
Code¶
In [13]:
Copied!
def sorted_squares(integers_list):
squares_list = []
for number in integers_list:
square = number*number
squares_list.append(square)
sorted_squares_list = sorted(squares_list)
return sorted_squares_list
def sorted_squares(integers_list):
squares_list = []
for number in integers_list:
square = number*number
squares_list.append(square)
sorted_squares_list = sorted(squares_list)
return sorted_squares_list
Verify Code with Test Cases¶
In [14]:
Copied!
assert sorted_squares([-3, 1, 9]) == [1, 9, 81 ]
assert sorted_squares([-3, 1, 9]) == [1, 9, 81 ]
In [15]:
Copied!
assert sorted_squares([-2, 0, 3]) == [0, 4, 9]
assert sorted_squares([-2, 0, 3]) == [0, 4, 9]