gpt4 book ai didi

python - 合并两个排序列表时,为什么我会得到两个不同的输出 (Python)

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:07:33 25 4
gpt4 key购买 nike

我很困惑为什么我在更改关系运算符时会得到两个不同的输出:

这是错误的版本:

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]

关于python - 合并两个排序列表时,为什么我会得到两个不同的输出 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31708543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com