Python中最简单的mergesort实现,有类型问题

时间:2015-10-01 15:42:06

标签: python sorting mergesort

我为学习目的编写了一个简单的mergesort实现,但它确实没有用。即使我一步一步地查看代码,我也不知道为什么会出现类型问题。这是我的代码:

def mergesort(seq):
    if len(seq)<2:
        return seq
    else:
        m = len(seq)//2
        return merge(mergesort(seq[:m]), mergesort(seq[m:]))

def merge(low, high):
    res = []
    i, j = 0, 0
    while i<len(low) and j<len(high):
        if low[i] <= high[j]:
            res.append(low[i])
            i = i+1
        else:
            res.append(high[j])
            j = j+1
    res.append(low[i:])
    res.append(high[j:])
    return res

这就是python-shell返回的内容:

>>> mergesort([5,8,1,3,99,5,2,3,4,9,7,5,8])
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    mergesort([5,8,1,3,99,5,2,3,4,9,7,5,8])
  File "D:\Documents\alp2\py2.py", line 6, in mergesort
    return merge(mergesort(seq[:m]), mergesort(seq[m:]))
  File "D:\Documents\alp2\py2.py", line 6, in mergesort
    return merge(mergesort(seq[:m]), mergesort(seq[m:]))
  File "D:\Documents\alp2\py2.py", line 6, in mergesort
    return merge(mergesort(seq[:m]), mergesort(seq[m:]))
  File "D:\Documents\alp2\py2.py", line 12, in merge
    if low[i] <= high[j]:
TypeError: unorderable types: int() <= list()
>>>

1 个答案:

答案 0 :(得分:2)

问题主要是因为行 -

res.append(low[i:])
res.append(high[j:])

此处,切片返回list,然后您将这些返回的列表追加到res列表中,并返回此res列表。因此,在某个时候,它会尝试将上面添加的list与导致您遇到问题的整数进行比较。

将列表中的元素添加为res列表的元素。您应该使用list.extend()代替.append()。示例 -

res.extend(low[i:])
res.extend(high[j:])

演示 -

>>> def mergesort(seq):
...     if len(seq)<2:
...         return seq
...     else:
...         m = len(seq)//2
...         return merge(mergesort(seq[:m]), mergesort(seq[m:]))
...
>>> def merge(low, high):
...     res = []
...     i, j = 0, 0
...     while i<len(low) and j<len(high):
...         if low[i] <= high[j]:
...             res.append(low[i])
...             i = i+1
...         else:
...             res.append(high[j])
...             j = j+1
...     res.extend(low[i:])
...     res.extend(high[j:])
...     return res
...
>>>
>>> mergesort([10,12,55,22,100])
[10, 12, 22, 55, 100]
>>> mergesort(list(range(100,50,-10)))
[60, 70, 80, 90, 100]