python - 关于在返回无的列表中查找子序列的代码
问题描述
此代码应该返回存在于列表“单词”中的最长字符串子序列(如果可以从 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))```
解决方案
取决于您到底在寻找什么,这可能会有所帮助:
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)
可能会派上用场。此外,还不清楚子字符串是否必须是连续的(因为这会返回)(可能是您的描述中的情况)。
推荐阅读
- java - 添加通过用户输入决定的数组元素
- vba - 真的没有办法计算连接到 OLAP 数据源的 Slicer 中 Visible Slicer Items 的数量吗?
- sql - PostgreSQL - 查询表中列中的关键字模式
- pentaho - 是否可以用 Pentaho BI Server 中的社区文件存储库替换 Jackrabbit 存储库
- rxjs - Axios 上的 RxJS Observable 如何访问响应
- c# - C#的C++ qsort算法?
- python-3.x - 如何在 Python 中使用 Selenium webdriver 提取文本?
- node.js - 通过 Node.Js 连接 mongoDB 时出现 MongoNetworkError
- css - 为什么我的设备分辨率 / devicePixelRatio 不等于我的 CSS 的视口宽度?
- .net - VB .NET - datatable.SELECT 过滤器问题