Square list of elements in sorted form in Python

PythonServer Side ProgrammingProgramming

Suppose we have a sorted list of numbers; we have to square each element and find the output in sorted order. We can also put negative numbers and 0 as input.

So, if the input is like [-12,-6,-5,-2,0,1,2,4,8,9,10,15,18,20,35,38,69], then the output will be [0, 1, 4, 4, 16, 25, 36, 64, 81, 100, 144, 225, 324, 400, 1225, 1444, 4761]

To solve this, we will follow these steps −

  • make a new list L
  • for each element e in nums:
    • insert e^2 into L
  • return L in sorted order.

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      return sorted(x * x for x in nums)
ob = Solution()
nums = [1,2,4,8,9,10,15,18,20,35,38,69]
print(ob.solve(nums))

Input

[-12,-6,-5,-2,0,1,2,4,8,9,10,15,18,20,35,38,69]

Output

[ 1, 4, 4, 16, 25, 36, 64, 81, 100, 144, 225, 324, 400, 1225, 1444, 4761]
raja
Published on 23-Sep-2020 10:40:41
Advertisements