2012-03-26 31 views
2

我想写一个合并排序函数,它接受一个列表和比较功能,在Python:比较两个元组的第二个元素与“<”未能在Python

def sort(unsorted, comp_func=lambda x, y: x < y): 

    length = len(unsorted) 
    if length <= 1: return unsorted 

    halflen = length/2 
    lsorted= sort(unsorted[:halflen]) 
    rsorted = sort(unsorted[halflen:]) 
    combined = [] 

    while True: 
     if len(lsorted) > 0: 
      if len(rsorted) > 0 and comp_func(rsorted[0], lsorted[0]): 
       combined.append(rsorted[0]) 
       rsorted = rsorted[1:] 
      else: 
       combined.append(lsorted[0]) 
       lsorted = lsorted[1:] 
     elif len(rsorted) > 0: 
      combined.append(rsorted[0]) 
      rsorted = rsorted[1:] 
     else: 
      break 

    return combined 

它工作正常列表为int(使用默认的comp_func),以及当比较函数比较这样一个元组的第一个元素时具有2个元组的列表int

comp_func = lambda x, y: x[0] < y[0] 

但是,当我编写比较函数以通过元组的第二个元素进行比较时,返回的列表仍然是未排序的版本。

comp_func = lambda x, y: x[1] < y[1] 

但是,如果我改变“<”操作员“>”,这样的列表将被递减排序,它的工作原理:

comp_func = lambda x, y: x[1] > y[1] 

不知道为什么“<”失败在元组的第二个元素上...

已经搜索了可能的解释,我发现这个:Does python think 10 is less than 9。但是,情况并非如此;正在排序的列表包含元组int,而不是字符串

+0

你忘了测试向量(S)。 – 2012-03-26 03:23:53

回答

1

你实际上并不表明你是如何改变运营成绩单,所以这只是一个猜测,但是请注意,这两条线

lsorted= sort(unsorted[:halflen]) 
rsorted = sort(unsorted[halflen:]) 

不及格comp_func。所以,如果你做了这样的事情:

>>> sort([(3,4),(1,2), (2,3)]) 
[(1, 2), (2, 3), (3, 4)] 
>>> sort([(3,4),(1,2), (2,3)],lambda x,y: x[1] > y[1]) 
[(3, 4), (1, 2), (2, 3)] 

,你会得到不一致的结果,因为一半的时间它的排序与不同comp_func。在lsorted=rsorted=线穿境而comp_func修复此:

>>> sort([(3,4),(1,2), (2,3)],lambda x,y: x[1] > y[1]) 
[(3, 4), (2, 3), (1, 2)] 
+0

我明白了。只需将'comp_func'传递给这两个递归调用,就可以得到预期的结果。非常感谢!!! – rokux 2012-03-26 04:48:38

相关问题