Skip to content

Instantly share code, notes, and snippets.

@chiral
Last active January 30, 2017 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chiral/cb281b4c0359d0760a1e9f5ebc14768b to your computer and use it in GitHub Desktop.
Save chiral/cb281b4c0359d0760a1e9f5ebc14768b to your computer and use it in GitHub Desktop.
custom comparison function generator for sorted in Python
import numpy as np
from random import random
def cmp0(d):
def cmp(a,b):
return int(a[d]-b[d])
return cmp
def cmp1(dd):
def cmp(a,b):
for d in dd:
x,y=a[d],b[d]
if x!=y: return int(x-y)
return 0
return cmp
def dig(x,dd):
for d in dd:
x=x[d]
return x
def cmp2(ddd):
def cmp(a,b):
for dd in ddd:
x,y=dig(a,dd),dig(b,dd)
if x!=y: return int(x-y)
return 0
return cmp
def mycmp(dims,order='asc'):
dims=np.array(dims)
if dims.dtype!=np.dtype('int') or not np.all(dims>=0):
raise 'mycmp: dims should be array of positive int'
D=len(dims.shape)
if D>=3:
raise 'mycmp: depth of dims should be less than 3'
cmp=[cmp0,cmp1,cmp2][D](dims)
if order=='asc':
return cmp
if order=='desc':
return lambda b,a: cmp(a,b)
raise 'mycmp: order should be "asc" or "desc"'
if __name__ == '__main__':
xx=[[int(random()*5)
for i in range(3)]
for j in range(5)]
xxx=[[[int(random()*5)
for i in range(3)]
for j in range(5)]
for k in range(7)]
print 'DATA xx:'
print xx
print ''
print 'DATA xxx:'
print xxx
print ''
print 'TEST CASE 1: xx,mycmp(1)'
yy=sorted(xx,cmp=mycmp(1))
for y in yy: print y
print ''
print 'TEST CASE 2: xx,mycmp([1,2])'
yy=sorted(xx,cmp=mycmp([1,2]))
for y in yy: print y
print ''
print 'TEST CASE 3: xxx,mycmp([[1,2]])'
yyy=sorted(xxx,cmp=mycmp([[1,2]]))
for yy in yyy: print yy
print ''
print 'TEST CASE 4: xxx,mycmp([[0,1],[1,2]])'
yyy=sorted(xxx,cmp=mycmp([[0,1],[1,2]]))
for yy in yyy: print yy
print ''
#
# actually, the code above can be replaced with below
# we can specify some functions returning numeric tuple
#
print 'TEST CASE A: xx,lambda x: x[1]'
yy=sorted(xx,key=lambda x: x[1])
for y in yy: print y
print ''
print 'TEST CASE B: xx,lambda x: (x[1],x[2])'
yy=sorted(xx,key=lambda x: (x[1],x[2]))
for y in yy: print y
print ''
print 'TEST CASE C: xxx,lambda x: x[1][2]'
yy=sorted(xxx,key=lambda x: x[1][2])
for yy in yyy: print yy
print ''
print 'TEST CASE D: xxx,lambda x: (x[0][1],x[1][2])'
yyy=sorted(xxx,key=lambda x: (x[0][1],x[1][2]))
for yy in yyy: print yy
print ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment