sorted函数的实现
import random
hip=list(range(10))
random.shuffle(hip)
print(hip)
def hum(b,reverse=False):
hop=[]
for x in b:
for i,y in enumerate(hop):
flag= x>y if reverse else x<y
if flag:
hop.insert(i,x)
break
else:
hop.append(x)
return hop
print(hum(hip,True))
import random
hip=list(range(10))
random.shuffle(hip)
print(hip)
def hum(iterable,reverse=False):
hum=[]
def comp(a,b):
return a>b if reverse else a<b
for x in iterable:
for index,y in enumerate(hum):
if comp(x,y):
hum.insert(index,x)
break
else:
hum.append(x)
return hum
print(hum(hip,1))
将比较函数做成通用函数,外移
import random
hip=list(range(10))
random.shuffle(hip)
print(hip)
def comp(a,b,reverse):
return a>b if reverse else a<b
def hum(iterable,reverse=False):
hop=[]
for x in iterable:
for index,y in enumerate(hop):
if comp(x,y,reverse):
hop.insert(index,x)
break
else:
hop.append(x)
return hop
print(hum(hip,1))
hip=list(range(10))
random.shuffle(hip)
print(hip)
def comp(a,b):
return a<b
def hum(iterable,key=comp,reverse=False):
hip=[]
for x in iterable:
for index,y in enumerate(hip):
flag= key(x,y) if not reverse else key(y,x)
if flag:
hip.insert(index,x)
break
else:
hip.append(x)
return hip
print(hum(hip,reverse=True))