gpt4 book ai didi

python - 如何从 Python 中的一组列表中找到最长的匹配项?

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

如果我有这样一个列表

my_list = [1, 7, 3, 4, 2, 9, 6, 5, 8]

我还有其他长度小于 my_list 的列表。例如,假设我有如下两个其他列表:

my_other_list_1 = [1, 7, 3, 4, 2]
my_other_list_2 = [1, 7, 4, 9, 8]

所有列表都有不同的元素,其他列表有来自原始列表的元素。

我的问题是找到在 my_list 中具有最长匹配项的列表(my_other_list_1my_other_list_2)。首先请问这个问题叫什么?然后,我更喜欢获得每个列表的最长匹配项的长度。我该怎么做?

在这个例子中,我会返回 my_other_list_1 因为它有一个长度为 5 的匹配,因为 [1, 7, 3, 4, 2] 已经在 my_list 中。另外,我会为 my_other_list_2 返回 2,因为其中有一个长度为 2 的匹配项,即 [1, 7]

总结一下,如果我有一个算法 A 并且输入是 my_listmy_other_list_1my_other_list_2,该算法应该返回

my_other_list_1 has match 5
my_other_list_2 has match 2

注意。我认为这是一个称为最长公共(public)子序列 (LCS) 问题的问题,但据我所知,在 LCS 问题中,子序列不需要是连续的。

最佳答案

def longest_match(main_list, *other_lists, **options):
try:
if options:
ordered = options['ordered']
else:
raise Exception
except:
ordered = False

best_match = 0
longest_match = 0
for index, list in enumerate(other_lists):
current_match = 0
if not ordered:
while True:
if list[:current_match] == main_list[:current_match]:
current_match += 1
else:
if current_match > longest_match:
longest_match = current_match
best_match = index
break
else:
for i, letter in enumerate(list):
current_match = i
if letter == main_list[0]:
current_match += 1
while True:
if list[i:current_match] == main_list[:current_match]:
current_match += 1
else:
if current_match > longest_match:
longest_match = current_match
best_match = index
break
return other_lists[best_match]

print longest_match(my_list, my_other_list_1, my_other_list_2, ordered=True) #kwarg odered=True will allow for mid list comprehension

我在手机上并没有测试以下内容,但它应该可以解决问题!

关于python - 如何从 Python 中的一组列表中找到最长的匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37706839/

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