合并并使用排序合并排序列表 [英] Merge and sort a list using merge sort
问题描述
这是我的code
def merge_lists(all_lst):
if len(all_lst) < 2:
return all_lst[0] # get rid of the extra []
left = merge_lists(all_lst[:len(all_lst)//2]) #[[2, 7, 10]] ##[[0, 4, 6]]
right = merge_lists(all_lst[len(all_lst)//2:])#[[0, 4, 6], [3, 11]] ##[[3,11]]
def merge(left,right):
results = []
while left and right:
if left[0] < right[0]:
results.append(left[0])
left.remove(left[0])
else:
results.append(right[0])
right.remove(right[0])
results.extend(left)
results.extend(right)
return results
return merge(left, right)
我能够得到答案,当我把这个
I am able to get the answer when i put this
all_lst = [[2, 7, 10], [0, 4, 6], [3, 11]]
print(merge_lists(all_lst)) # [0, 2, 3, 4, 6, 7, 10, 11]
但是,当我试图改变它一点尚不工作
But when I tried to change it a little it doesn't work already
all_lst = [[2, 7, 10], [0, 4, 6], [3, 11, 1]]
print(merge_lists(all_lst)) ##[0, 2, 3, 4, 6, 7, 10, 11, 1]
我想知道什么是错
May I know what's wrong
推荐答案
第三个列表进行排序。当你做你的最后延长1插入 最终列表的末尾。 你叫合并之前,您应该排序您的名单。
The third list is not sorted. When you do your final extend the 1 is inserted into the end of the final list. You should sort your lists before you call merge.
换句话说,你的投入应该是:
In other words your input should be:
all_lst = [[2, 7, 10], [0, 4, 6], [1, 3, 11]]
他们的方式合并工作原理是,假设子列表是有序的。
They way merging works is that assumes that the sublists are ordered.
例如把那些两个列表:
left = [1, 3]
right = [2, 4]
results = []
合并是这样的:
merging goes like this:
if left[0] < right[0]:
results.append(left[0])
left.remove(left[0])
所以现在
results = [1]
left = [3]
right = [2,4]
但如果你有:
but if you had:
left = [3, 1]
right = [2, 4]
results = []
合并是这样的:
merging goes like this:
if left[0] < right[0]: #false
else:
results.append(right[0])
right.remove(right[0])
所以现在
results = [2]
left = [3,1]
right = [4]
所以你结束了一个无序的最终名单。
therefore you end up with an unordered final list.
这篇关于合并并使用排序合并排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!