此合并排序实现在此错误上失败:“if(left_list [0]< = right_list [0]):TypeError:unorderable types:int()< = list()。”
为什么right_list [0]被认为是一个列表而不是一个int?
def merge_sort(array):
def merge(left_list, right_list):
result = []
while len(left_list) > 0 or len(right_list) > 0:
if len(left_list) > 0 and len(right_list) > 0:
if (left_list[0] <= right_list[0]):
result.append(left_list[0])
left_list = left_list[1:]
else:
result.append(right_list[0])
right_list = right_list[1:]
elif len(left_list) > 0:
result.append(left_list)
left_list = left_list[1:]
elif len(right_list) > 0:
result.append(right_list[0])
right_list = right_list[1:]
return result
if len(array) < 2:
return array
i_mid = len(array)//2
left = array[:i_mid]
right = array[i_mid:]
left = merge_sort(left)
right = merge_sort(right)
result = merge(left, right)
return result
答案 0 :(得分:3)
错误:一个分支返回一个列表,当它应该是一个项目:)固定。
def merge_sort(array):
def merge(left_list, right_list):
result = []
while len(left_list) > 0 or len(right_list) > 0:
if len(left_list) > 0 and len(right_list) > 0:
if (left_list[0] <= right_list[0]):
result.append(left_list[0])
left_list = left_list[1:]
else:
result.append(right_list[0])
right_list = right_list[1:]
elif len(left_list) > 0:
result.append(left_list[0]) # <==
left_list = left_list[1:]
elif len(right_list) > 0:
result.append(right_list[0])
right_list = right_list[1:]
return result
if len(array) < 2:
return array
i_mid = len(array)//2
left = array[:i_mid]
right = array[i_mid:]
left = merge_sort(left)
right = merge_sort(right)
result = merge(left, right)
return result
print merge_sort([5,4,3,1,2])
[1, 2, 3, 4, 5]