Skip to content

Instantly share code, notes, and snippets.

@siddhantmedar
Created June 22, 2022 18:58
Show Gist options
  • Save siddhantmedar/c6502506e2189acb4d64dc667cbf6b87 to your computer and use it in GitHub Desktop.
Save siddhantmedar/c6502506e2189acb4d64dc667cbf6b87 to your computer and use it in GitHub Desktop.
Custom comparator implementation for sorting array
import functools
item = [4, 5, 13, 1, 2, 7]
def cmp(a, b):
if a < b:
return -1
elif a == b:
return 0
elif a > b:
return 1
def cmp2(a, b):
if a[0] < b[0]:
return -1
elif a[0] == b[0]:
if a[1] < b[1]:
return -1
elif a[1] == b[1]:
return 0
elif a[1] > b[1]:
return 1
elif a[0] > b[0]:
return 1
print(item)
nums_lst = sorted(item, key=functools.cmp_to_key(cmp))
print(nums_lst)
item= [(1,0),(2,51),(2,23),(1,-1)]
print(item)
nums_lst = sorted(item, key=functools.cmp_to_key(cmp2))
print(nums_lst)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment