gpt4 book ai didi

python - 关于在列表中查找子序列的代码不返回任何内容

转载 作者:太空宇宙 更新时间:2023-11-03 20:03:34 24 4
gpt4 key购买 nike

此代码应该返回“words”列表中存在的最长字符串子序列(如果可以从 S 中删除一些字符(可能为零)以形成 W,而无需重新排序,则单词 W 是 S 的子序列其余字符)。但它对任何输入值都返回 None ,我不明白为什么。有什么建议吗?

string = input()
words = (input()).split()
def longest_subsequence (string, words):
words = list(words)
max_length = 0
max_sub = ""
for i in range(len(words)):
ind = i
isSubsequence = True
for j in words[i]:
if j == string[ind]:
ind +=1
else:
isSubsequence = False
break
if isSubsequence and max_length < len(words[i].split()):
max_length = len(words[i].split())
max_sub = words[i]
return max_sub
print (longest_subsequence(string, words))```

最佳答案

这是你出错的地方:

if isSubsequence and max_length < len(words[i].split()):
max_length = len(words[i].split())
max_sub = words[i]

这个条件语句只执行一次,因为最初 isSubsequence是真的并且 max_length为零。所以max_sub仅当子序列是单词列表中的第一个单词时才返回。对于其他迭代max_length < len(words[i].split()) len(words[i].split()) 永远不会成立总是返回 1。你应该尝试这个:

string = input()
words = (input()).split()
def longest_subsequence (string, words):
words = list(words)
max_length = 0
max_sub = ""
for i in range(len(words)):
ind = 0
isSubsequence = True
for j in words[i]:
if j == string[ind]:
ind +=1
else:
isSubsequence = False
break
if isSubsequence and len(words[i]) > max_length:
max_length = len(words[i].split())
max_sub = words[i]
return max_sub
print (longest_subsequence(string, words))

关于python - 关于在列表中查找子序列的代码不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59095356/

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