Jmu*_*uru 3 python algorithm merge sorted
我很困惑为什么在更改关系运算符时我得到两个不同的输出:
这是不正确的版本:
listOne = [1,3,6,9,11]
listTwo = [2,4,5,7,8,10,12]
def mergeTwo(l1,l2):
output = []
while l1 and l2:
if l1[0] > l2[0]:
output.append(l2.pop(0))
output.append(l1.pop(0))
if l1:
output.extend(l1)
elif l2:
output.extend(l2)
print output
Run Code Online (Sandbox Code Playgroud)
输出是:
[1, 2, 3, 4, 6, 5, 9, 7, 11, 8, 10, 12]
但是当我这样做时它会起作用:
listOne = [1,3,6,9,11]
listTwo = [2,4,5,7,8,10,12]
def mergeTwo(l1,l2):
output = []
while l1 and l2:
if l1[0] < l2[0]:
output.append(l1.pop(0))
output.append(l2.pop(0))
if l1:
output.extend(l1)
elif l2:
output.extend(l2)
print output
Run Code Online (Sandbox Code Playgroud)
我将运算符更改为<和弹出的元素的顺序,我得到此输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Run Code Online (Sandbox Code Playgroud)
为什么第二个版本正确地合并了两个列表?
两种解决方案实际上都是错 第二个恰好适合您的特定输入.
它们是错误的,因为你首先检查某个元素是否小于其他列表中的相同索引元素,然后添加较小的元素,然后你去另外列表中添加元素,而不检查下一个第一个列表中的索引元素是否较小.
这是第一个不起作用的主要原因.第二个适用于您的特定输入 -
listOne = [1,3,6,9,11]
listTwo = [2,4,5,7,8,10,12]
Run Code Online (Sandbox Code Playgroud)
因为每个元素listTwo都小于下一个索引元素listOne.在不是这种情况下给出输入,你会看到错误的结果.
正确的方法 -
def mergeTwo(l1,l2):
output = []
while l1 and l2:
if l1[0] < l2[0]:
output.append(l1.pop(0))
else:
output.append(l2.pop(0))
if l1:
output.extend(l1)
elif l2:
output.extend(l2)
print output
Run Code Online (Sandbox Code Playgroud)
示例/演示 -
>>> listOne = [1,3,6,9,11]
>>> listTwo = [2,4,5,7,8,10,12]
>>>
>>> def mergeTwo(l1,l2):
... output = []
... while l1 and l2:
... if l1[0] < l2[0]:
... output.append(l1.pop(0))
... else:
... output.append(l2.pop(0))
... if l1:
... output.extend(l1)
... elif l2:
... output.extend(l2)
... print(output)
...
>>> mergeTwo(listOne,listTwo)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> listOne = [1,3,6,9,11]
>>> listTwo = [10,15,20,25,30]
>>> mergeTwo(listOne,listTwo)
[1, 3, 6, 9, 10, 11, 15, 20, 25, 30]
Run Code Online (Sandbox Code Playgroud)