python - 如何为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')
解决方案
我认为您缺少 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
推荐阅读
- android - {NS} 如何调试安装在工作配置文件中的应用程序?
- java - 如何在 java 中重新制作这个数组?
- python - Python错误地将文件扩展名添加到路径字符串
- mysql - 如何对计数查询求和
- vue.js - 使用帖子正文重定向 VueJs 组件
- python - 如何从 .txt 文件创建数组?
- typo3 - TYPO3 11 Sitepackage 教程预期模板文件 Standard/1.html
- vim - 如何让vim正确显示jq报错?
- php - phpseclib 使用 nlist() 函数时不显示来自 SFTP 的目录内容,但会引发 LengthException
- javascript - `npm start` 正确显示网站,但是使用`npm build` 构建时,缺少很多信息