首页 > 解决方案 > 如何为python中的变量分配返回值?

问题描述

我一直在研究二进制插入排序,但遇到了一个问题。它一直告诉我,在第二个 for 循环之前的“binary_insertion_sort”函数中,“NoneType”对象不能被解释为整数。谁能解释我的代码有什么问题并告诉我其中是否有任何逻辑错误?

def binary_search(n, bin_list, low, high):
    print(low,high)
    if high - low <= 1:
        if n < bin_list[low]:
            return low - 1
        elif n > bin_list[high]:
            print('d',n,high)
            return high + 1
        elif n == bin_list[low]:
            return low
        elif n== bin_list[high]:
            return high
        else:
            print('c',low)
            return low+1
    mid = (low+high)//2
    print('a',mid)
    if n < bin_list[mid]:
        binary_search(n, bin_list, 0, mid-1)
    elif n > bin_list[mid]:
        binary_search(n, bin_list, mid+1, high)
    else:
        return mid

binary_insertion_sort 部分

def binary_insertion_sort(text):
    sorted_list = text.split()
    for num in range(1, len(sorted_list)):
        unsorted = sorted_list[num]
        print(sorted_list)
        index = binary_search(unsorted, sorted_list, 0, len(sorted_list)-1)
        for  j in range(num, index, -1):
            print(j)
            sorted_list[j] = sorted_list[j-1]
            sorted_list[index-1] = num
    return sorted_list

a = binary_insertion_sort('1 2 3 4 5')

标签: pythonfunctionreturn-valuebinary-searchreturn-type

解决方案


我认为您缺少 binary_search 函数中递归案例的返回。

当函数在最后一个 if 中进入前两种情况之一时:

if n < bin_list[mid]:
    binary_search(n, bin_list, 0, mid-1)
elif n > bin_list[mid]:
    binary_search(n, bin_list, mid+1, high)
else:
    return mid

您正在将 None (函数返回类型)分配给索引 var。您应该尝试使用:

if n < bin_list[mid]:
    return binary_search(n, bin_list, 0, mid-1)
elif n > bin_list[mid]:
    return binary_search(n, bin_list, mid+1, high)
else:
    return mid

推荐阅读