python - 实现归并排序算法以升序对数字列表进行排序
问题描述
我试图在python中实现合并排序,这就是我得到的:
def merge_sort(num_list):
if len(num_list) < 2:
return num_list
else:
mid = len(num_list) // 2
left_list = merge_sort(num_list[: mid])
right_list = merge_sort(num_list[mid: ])
merge(left_list,right_list)
def merge(left_list,right_list):
sorted_list = []
i = j = 0
while (i < len(left_list) and j < len(right_list)):
if left_list[i] <= right_list[j]:
sorted_list.append(left_list[i])
i += 1
else:
sorted_list.append(right_list[j])
j += 1
while(i < len(left_list)):
sorted_list.append(left_list[i])
i += 1
while j < len(right_list):
sorted_list.append(right_list[j])
j += 1
return sorted_list
我收到了这个错误信息:
Traceback (most recent call last):
line 34, in <module>
sorted_list = merge_sort(num_list)
line 9, in merge_sort
left_list=merge_sort(num_list[:mid])
line 12, in merge_sort
merge(left_list,right_list)
line 18, in merge
while i<len(left_list) and j<len(right_list):
TypeError: object of type 'NoneType' has no len()
有人可以帮我理解代码中出了什么问题,我该如何解决?
解决方案
You're not returning the merged list in your merge_sort
method in your else
condition. The following change will make your function work correctly (note the return
at the end):
def merge_sort(num_list):
if len(num_list) < 2:
return num_list
mid = len(num_list) // 2
left_list = merge_sort(num_list[: mid])
right_list = merge_sort(num_list[mid: ])
return merge(left_list,right_list)
推荐阅读
- python - Python将矩阵转换为列表
- javascript - 增量计数器 Chrome 扩展批处理 (Javascript)
- php - simplexml_load_file/simplexml_load_string 都返回错误信息
- snowflake-cloud-data-platform - 在雪花中切换用户角色
- python - 如何在达到一个值时执行一次代码并继续循环直到达到下一个值?
- javascript - axios - node.js - 如何使用等待/异步添加动态请求的延迟
- javascript - swiperjs init 后可以修改slidesPerView 的数量吗?
- php - 如果标签中的路由不执行任何操作,则控制器仅适用于表单
- python - 'collections.OrderedDict' 对象没有属性
- java - Spring data Mongo Audit 字段反映在嵌套文档中