问题
This is my 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.
For example take those two lists:
left = [1, 3]
right = [2, 4]
results = []
merging goes like this:
if left[0] < right[0]:
results.append(left[0])
left.remove(left[0])
so now
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])
so now
results = [2]
left = [3,1]
right = [4]
therefore you end up with an unordered final list.
来源:https://stackoverflow.com/questions/22440361/merge-and-sort-a-list-using-merge-sort