I want to write a custom key function for a question I saw at Pramp. I am used to using something like:
my_list.sort(key = lambda x: (x[1], -x[0]))
This time I need a more complicated key function, and I realized that I don't know how to write it. How can I write such a key function for sorting in Python3? Which value should key function return? What should its input be?
My key function (not working)
def key_function(num1, num2):
if abs(num1) < abs(num2):
return num1
if abs(num1) > abs(num2):
return num2
if num1 < num2:
return num1
if num1 > num2:
return num2
if num1 == num2:
return num1
From Pramp:
If two numbers have the same absolute value, sort them according to sign, where the negative numbers come before the positive numbers.
input: arr = [2, -7, -2, -2, 0]
output: [0, -2, -2, 2, -7]
Their pseudo code answer:
def compare(a, b):
if abs(a) < abs(b): return -1
if abs(a) > abs(b): return 1
if a < b: return -1
if a > b: return 1
return 0
arr.sort(cmp = compare)
return arr