gpt4 book ai didi

python - 如何在列表中按字母顺序取出最长的子串?

转载 作者:行者123 更新时间:2023-12-04 02:31:51 25 4
gpt4 key购买 nike

比如初始列表L=["by","article","circle","for","line","dance","effort"],我想取出["article","circle","for","line"] 作为结果。因为 L 中的第一个 alpha 是 (b,a,c,f,l,d,e) 并且 (a,c,f,l) 的结果比 (d,e) 长,所以结果是 [ “文章”,“圈子”,“为”,“线”]。如何修复我的代码?我是新手,所以我对 sorted() 和嵌套循环感到很困惑。

def find_longest_consisting(test_case):
if not test_case:
return []
result = []
for i in range(len(test_case)):
for j in range(i + len(result) + 1):
substring = test_case[i:j]
if len(substring) != (j - i):
break
if sorted(substring) == list(substring):
result = substring
return result

test_cases = ["by","article","circle","for","line","dance","effort"]
test_result = find_longest_consisting(test_cases)
print(test_result)

最佳答案

最快的方法是维护一个“最长”列表,并在遇到排序变化时将其长度与当前子列表进行比较,如果当前子列表更长,则将其分配给最长的。这只需要对列表进行一次迭代即可获得结果。

def longest_group(lst):
longest = []
current = lst[:1]
for i in range(1, len(lst)):
if lst[i][0] <= lst[i-1][0]:
if len(current) > len(longest):
longest = current
current = [lst[i]]
else:
current.append(lst[i])
if len(current) > len(longest):
longest = current
return longest

print(longest_group(["by","article","circle","for","line","dance","effort"]))
print(longest_group(["zoo","slack","egg"]))

输出:

['article', 'circle', 'for', 'line']
['zoo']

对于您的 ["by","article","circle","for","line","dance","effort"] 列表,这比排序所有的快 10 倍列表中的组合。参见 https://rextester.com/JEJOAE73859用于演示。

关于python - 如何在列表中按字母顺序取出最长的子串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63785854/

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