首页 > 解决方案 > 关于在返回无的列表中查找子序列的代码

问题描述

此代码应该返回存在于列表“单词”中的最长字符串子序列(如果可以从 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))```

标签: python

解决方案


取决于您到底在寻找什么,这可能会有所帮助:

def substrings(word):
    for i in range(len(word)):
        for j in range(len(word),0,-1):
            new_word = word[i:j]
            if new_word:
                yield new_word

def subseqs(string,sentence):
    words = sentence.split()
    sbstrs = [s for s in substrings(string)]
    for word in words:
        subseqs = [s for s in sbstrs if s in word]
        print(subseqs)

这让你:

print(subseqs('ban','my banana has been banned'))
[]
['ban', 'ba', 'b', 'an', 'a', 'n']
['a']
['b', 'n']
['ban', 'ba', 'b', 'an', 'a', 'n']

我不清楚您是否需要将子字符串包含在所有单词中,这只是查找每个单词中的所有子字符串,从中可以找到最长的子字符串 - 取决于您是想要单个答案还是全部等长如果有多个,则为子字符串。如果您只想要可能许多最长的子字符串之一,那么max(subseqs, key=len)可能会派上用场。此外,还不清楚子字符串是否必须是连续的(因为这会返回)(可能是您的描述中的情况)。


推荐阅读