gpt4 book ai didi

python - 一对列表中的最小对列表

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

给定两个整数列表,生成最短的对列表,其中两个列表中的每个值都存在。每对中的第一个必须是第一个列表中的值,每对中的第二个必须是第二个列表中的值。每对中的第一个必须小于第二个。

如果列表的长度不同,或者如果每个列表中的相同位置存在相同的整数,则简单的 zip 将不起作用。

def gen_min_pairs(uplist, downlist):
for pair in zip(uplist, downlist):
yield pair

这是我目前能想到的:

def gen_min_pairs(uplist, downlist):
up_gen = iter(uplist)
down_gen = iter(downlist)

last_up = None
last_down = None

while True:
next_out = next(up_gen, last_up)
next_down = next(down_gen, last_down)

if (next_up == last_up and
next_down == last_down):
return

while not next_up < next_down:
next_down = next(down_gen, None)
if next_down is None:
return
yield next_up, next_down

last_up = next_up
last_down = next_down

这是一个简单的测试例程:

if __name__ == '__main__':
from pprint import pprint

datalist = [
{
'up': [1,7,8],
'down': [6,7,13]
},
{
'up': [1,13,15,16],
'down': [6,7,15]
}
]

for dates in datalist:
min_pairs = [pair for pair in
gen_min_pairs(dates['up'], dates['down'])]
pprint(min_pairs)

该程序为第一组日期生成预期输出,但为第二组生成失败。

预期:

[(1, 6), (7, 13), (8, 13)]
[(1, 6), (1, 7), (13, 15)]

实际:

[(1, 6), (7, 13), (8, 13)]
[(1, 6), (13, 15)]

我认为这可以在只查看每个列表的每个元素一次的情况下完成,因此复杂度为 O(len(up) + len(down))。我认为这取决于每个列表唯一的数字元素。

编辑:我应该补充一点,我们可以期望这些列表首先按最小整数排序。

编辑:uplistdownlist 只是任意名称。 AB 可能不太容易混淆。

此外,这里还有一个更健壮的测试例程:

from random import uniform, sample
from pprint import pprint

def random_sorted_sample(maxsize=6, pop=31):
size = int(round(uniform(1,maxsize)))
li = sample(xrange(1,pop), size)
return sorted(li)

if __name__ == '__main__':
A = random_sorted_sample()
B = random_sorted_sample()

min_pairs = list(gen_min_pairs(A, B))

pprint(A)
pprint(B)
pprint(min_pairs)

这会生成随机现实输入、计算输出并显示所有三个列表。以下是正确实现会产生的结果的示例:

[11, 13]
[1, 13, 28]
[(11, 13), (13, 28)]

[5, 15, 24, 25]
[3, 13, 21, 22]
[(5, 13), (15, 21), (15, 22)]

[3, 28]
[4, 6, 15, 16, 30]
[(3, 4), (3, 6), (3, 15), (3, 16), (28, 30)]

[2, 5, 20, 24, 26]
[8, 12, 16, 21, 23, 28]
[(2, 8), (5, 12), (5, 16), (20, 21), (20, 23), (24, 28), (26, 28)]

[3, 4, 5, 6, 7]
[1, 2]
[]

最佳答案

我有很多想法来解决这个问题(参见编辑历史 ;-/),但没有一个能完全解决或在线性时间内完成。我花了一段时间才看到它,但我有 a similar problem before所以我真的很想弄明白 ;-)

无论如何,当我放弃直接这样做并开始绘制有关匹配的图表时,最终解决方案出现了。我认为您的第一个列表只是定义了间隔,您正在寻找属于它们的项目:

def intervals(seq):
seq = iter(seq)
current = next(seq)
for s in seq:
yield current,s
current = s
yield s, float("inf")

def gen_min_pairs( fst, snd):
snd = iter(snd)
s = next(snd)
for low, up in intervals(fst):
while True:
# does it fall in the current interval
if low < s <= up:
yield low, s
# try with the next
s = next(snd)
else:
# nothing in this interval, go to the next
break

关于python - 一对列表中的最小对列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4304976/

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