简体   繁体   English

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

[英]TypeError: object of type 'NoneType' has no len()

I am attempting a mergesort algorithm and I am receiving this type error: 我正在尝试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()

... on this code: ...在这段代码上:

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)

You forget the return in your merge function: 您忘记了合并函数中的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

Note that this merge function is incorrect. 请注意,此merge功能不正确。 If left and right have different lengths then result will not contain all the elements of both lists. 如果leftright有不同的长度,然后result包含两个列表中的所有元素。 (because one of the indices, say i , will fail the condition of i < len(left) when j didn't scan the whole right list). (因为当j没有扫描整个right列表时,其中一个索引,比如i ,将失败i < len(left)的条件。 This will always happen, since the while loop increases only one index at a time, which means that at some point you can have i = len(left) - 1 and j = len(right) - 1 but only one of i and j will be incremented in the next iteration, and one of the two conditions will be False , causing the loop to stop. 这将永远发生,因为while循环一次只增加一个索引,这意味着在某些时候你可以有i = len(left) - 1j = len(right) - 1但只有ij将在下一次迭代中递增,并且两个条件之一将为False ,从而导致循环停止。

See: 看到:

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

Adding: 添加:

result.extend(left[i:] or right[j:])

before the return should fix this problem: 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM