python中的合并排序有什么问题?

python中的合并排序有什么问题?,python,mergesort,Python,Mergesort,我正试图写合并排序,却被困在这里 我的代码有什么问题?我试图在不引用任何资源的情况下实现它,并且不必要地编写这行代码,因为Stackoverflow中的一些愚蠢规则迫使我解释我的代码 def merge_sort(A): if len(A) <= 1: return A #split list in 2 mid = len(A)/2 B = A[:mid] C = A[mid:] B = merge_sort(B)

我正试图写合并排序,却被困在这里

我的代码有什么问题?我试图在不引用任何资源的情况下实现它,并且不必要地编写这行代码,因为Stackoverflow中的一些愚蠢规则迫使我解释我的代码

def merge_sort(A):
    if len(A) <= 1:
        return A

    #split list in 2
    mid = len(A)/2
    B = A[:mid]
    C = A[mid:]

    B = merge_sort(B)
    C = merge_sort(C)

    #merge
    result = []
    while len(B) > 0 and len(C) > 0:
        if B[0] > C[0]:
            result.append(C.pop(0))
        else:
            result.append(B.pop(0))

    if len(B) > 0:
        result.extend(merge_sort(B))
    else:
        result.extend(merge_sort(C))



print merge_sort([8, 2, 1, 1, 4, 45, 9, 3])
我得到这个错误:

Traceback (most recent call last):
  File "merge_sort.py", line 31, in <module>
    print merge_sort([8, 2, 1, 1, 4, 45, 9, 3])
  File "merge_sort.py", line 11, in merge_sort
    B = merge_sort(B)
  File "merge_sort.py", line 16, in merge_sort
    while len(B) > 0 and len(C) > 0:
TypeError: object of type 'NoneType' has no len()

合并排序函数需要

return result 

最后,但事实并非如此。函数在默认情况下不返回任何值,这就是出现错误的原因。

您忘记在函数末尾写入返回结果。如果没有该行,函数将返回None,这将最终导致一个lenNone和随后的TypeError:类型为“NoneType”的对象没有len。

-1表示哑规则注释。