TypeError:'NoneType'类型的对象没有len()

时间:2013-09-06 06:57:54

标签: python python-3.x mergesort

我正在尝试使用mergesort算法,我收到此类错误:

Input #1: [3, 1, 2, 5, 9, 6, 7]
Traceback (most recent call last):
  File "Lab1.py", line 24, in <module>
    print('Output #1: ' + mergesort(a))
  File "Lab1.py", line 18, in mergesort
    left = mergesort(lst[:middle])
  File "Lab1.py", line 20, in mergesort
    return merge(left, right)
  File "Lab1.py", line 6, in merge
    while i < len(left) and j < len(right):
TypeError: object of type 'NoneType' has no len()

...关于此代码:

def merge(left, right):
    result = []
    i, j = 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1

def mergesort(lst):
    if len(lst) <= 1:
        return lst
    middle = int(len(lst) / 2)
    left = mergesort(lst[:middle])
    right = mergesort(lst[middle:])
    return merge(left, right)

a = [3,1,2,5,9,6,7]
print 'Input #1: ' + str(a)
print 'Output #1: ' + mergesort(a)

1 个答案:

答案 0 :(得分:2)

您忘记了合并功能中的return

def merge(left, right):
    result = []
    i, j = 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    return result

请注意,此merge函数不正确。如果leftright的长度不同,则result包含两个列表的所有元素。 (因为当i未扫描整个i < len(left)列表时,其中一个索引(例如j)将失败right的条件。 这将始终发生,因为while循环一次只增加一个索引,这意味着在某些时候您可以i = len(left) - 1j = len(right) - 1但只有i中的一个并且j将在下一次迭代中递增,并且两个条件之一将为False,从而导致循环停止。

请参阅:

In [2]: mergesort(list(range(17)))
Out[2]: [0]

添加:

result.extend(left[i:] or right[j:])
return解决此问题之前

In [4]: mergesort(list(range(17)))
Out[4]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]