Why not to Overwrite Input in Python Functions

* Given an integer array `nums` sorted in non-decreasing order 
* Return:
* an array of the squares of each number sorted in non-decreasing order.

Example

Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
  • I provide an analysis of a solution that also does not use a built-in sort/ed functions

OVERWRITE INPUT

  • watch out for this !
  • this means that your input will be mutated by the function - even after it is complete
def ssa3(l):
print("before ", l)
for i in range(len(l)):
l[i] *= l[i]
print("after square:", l)
l.sort()
return print("after sort of squared:", l)
<!-- EXAMPLE -->
>>> inp = [-1,0,3,4]

>>> ssa3(inp)
before [-1, 0, 3, 4]
after square: [1, 0, 9, 16]
after sort of squared: [0, 1, 9, 16]

[0, 1, 9, 16] <<< YOUR INPUT IS AROUND WITH DIFFERENT VALUES THEN BEFORE


>>> ssa3(inp)
before [0, 1, 9, 16]
after square: [0, 1, 81, 256]
after sort of squared: [0, 1, 81, 256]

>>> ssa3(inp)
before [0, 1, 81, 256]
after square: [0, 1, 6561, 65536]
after sort of squared: [0, 1, 6561, 65536]

DO NOT OVERWRITE INPUT

  • a list comprehension nested in a built-in sorted function
def ssa4(l):
return sorted([v**2 for v in l])
>>> ssa4(inp)
ssa2: [0, 1, 9, 16]

>>> inp
[-1, 0, 3, 4]


>>> ssa4(inp)
ssa2: [0, 1, 9, 16]

>>> inp
[-1, 0, 3, 4]


>>> ssa4(inp)
ssa2: [0, 1, 9, 16]

>>> inp
[-1, 0, 3, 4]

TWO POINT ALGO WITH HELPER DATASTRUCTURE AND BACKWARD TRAVERSAL WITH THE RANGE FUNCTION

SOURCES

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com