标签:sorted python algorithm merge
我很困惑为什么在更改关系运算符时我得到两个不同的输出:
这是不正确的版本:
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
输出是:
[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
我将运算符更改为<弹出的元素的顺序,我得到这个输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
为什么第二个版本正确地合并了两个列表?
解决方法:
两种解决方案实际上都是错第二个恰好适合您的特定输入.
它们是错误的,因为你首先检查某个元素是否小于其他列表中的相同索引元素,然后添加较小的元素,然后你去添加其他列表中的元素,而不检查下一个第一个列表中的索引元素是否较小.
这是第一个不起作用的主要原因.第二个适用于您的特定输入 –
listOne = [1,3,6,9,11]
listTwo = [2,4,5,7,8,10,12]
因为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
示例/演示 –
>>> 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]
标签:sorted,python,algorithm,merge 来源: https://codeday.me/bug/20190824/1709008.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。