合并排序不能正常工作。我从无类型中收到错误

问题描述 投票:0回答:0
def merge(a, b):
    tempa = a
    tempb = b
    finallist = []
    while tempa != [] and tempb != []:
        i, j = 0, 0
        if a[i] <= b[j]:
            finallist += [tempa[i]]
            tempa.pop(i)
            j += 1
        elif a[i] > b[j]:
            finallist += [tempb[j]]
            tempb.pop(j)
            i += 1
    if tempa == [] and tempb != []:
        finallist.extend(tempb)
    elif tempa != [] and tempb == []:
        finallist.extend(tempa)
    return finallist

def mergeSort(lst):
    if len(lst) == 1:
        return lst
    mid = len(lst)//2
    left = lst[:mid]
    right = lst[mid:]
    print(left, right)
    mergedright = mergeSort(right)
    mergedleft = mergeSort(left)
    merge(mergedleft, mergedright)

mergeSort([-3,10,29,7,3,0,-3,11])

根据pycharm,错误在于

        if a[i] <= b[j]:

我插入了一些打印件来找出哪个左,哪个右以及哪个相应的 mergedleft 和 mergedright 给我错误。好像错误前的(left, right)的最后一个值是[3], [0]而(mergedleft, mergedright)的最后一个值是None, None 这让我觉得我的 mergeSort 无法处理 [3] 和 [0],但是当分别测试这些情况时它工作正常。

python mergesort
© www.soinside.com 2019 - 2024. All rights reserved.