using std::vector;
using std::sort;
using std::copy;
using std::swap;
using std::ostream_iterator;
using std::greater;
using std::less;
using std::iterator_traits;
class UpSort:
def sort (self,List,CompareFucntion):
"对一个列表依据自定义的比较函数作升排序"
for k in List:
for o in List:
if getattr(self,CompareFucntion )(k,o)==1:
temp=List[List.index(k)]
List[List.index(k)]=o
List[List.index(o)]=temp
class DownSort:
def sort (self,List,CompareFucntion):
"对一个列表依据自定义的比较函数作升排序"
for k in List:
for o in List:
if getattr(self,CompareFucntion )(k,o)==0:
temp=List[List.index(k)]
List[List.index(k)]=o
List[List.index(o)]=temp
但是在PYTHON中间的实现完全靠PYTHON的Mix_in.MySort类一开始没有任何SORT的功能,当我用Mix_in特性为MYSORT上加上一个DOWNSORT然后生成的对象就具有DOWNSORT功能,当我把DOWNSORT卸载掉然后加入UPSORT功能它又能加上UPSORT功能。这样的Mix_in的特性当然在C++或者JAVA中都可以用继承来实现但是继承就带来了结构上的臃肿和冗余,可能我要DOWNSORT而不要UPSORT的时候在C++或者JAVA中无论如何都要为一个类定义两种功能而PYTHON你可以随时装配。PYTHON就好比是一个可拆卸的自行车,用GP的思想实现各种各样的算法然后用过Mix_in特性装配到你需要的地方。而c++或者java只能是要多少装多少的重型卡车。PYTHON及能够实GP的现数据与算法的分离又降低了继承的层次性。
另外Python的动态语义特性能够比c++的函数指针能更好的处理gp中的抽象。
在sort函数中python通过系统函数getattr的来识别由CompareFucntion传入的函数字符串比如我传入"mycmp"然后getattr就能够得到mycmp的运行实例后面加两个参数就能够正确的运行函数
def sort (self,List,CompareFucntion):
"对一个列表依据自定义的比较函数作升排序"
for k in List:
for o in List:
if getattr(self,CompareFucntion )(k,o)==1:
在stl中相同的功能是这样处理的
sort(vectro.being(),vector.end(),mycmp)
他通过函数指针来处理
这样做的最大的好处在于可以避免冗长的switch case或者if else语句
另外python同样可以模拟c++的stl譬如我把上面的程序改成如下的
方式和c++中的一样除了没有用template以外
def sort (List,CompareFucntion):
"对一个列表依据自定义的比较函数作升排序"
for k in List[:]:
for o in List[:]:
if apply(CompareFucntion,(k,o))==0:
temp=k
List[List.index(o)]=temp
List[List.index(k)]=o
def upcmp(p,q):
"自定义比较函数"
if p>=q:
return 1
else:
return 0
def downcmp(p,q):
"自定义比较函数"
if p>=q:
return 0
else:
return 1
def excuteSort():
li=[5,8,45,2,68,90,12,67,23,89,29,38,0]
sort(li,upcmp)
print li
sort(li,downcmp)
print li