python - 使用字符串方法在第二个单词中查找一个单词的出现
问题描述
所以我有一个函数,它接收两个只有字母的单词,如果第二个单词出现在第一个单词中的顺序与单词中的顺序完全相同,则返回 True。
例如,如果我有:
>>> within('builder','bild')
它会以 bild 的形式返回 True,出现在第一个单词中,与第二个单词中的顺序相同。
虚假陈述的一个例子是:
>>> within('builder', 'bidl')
因为即使 word2 中的字母在 word1 中,它们的顺序也不同。
我试图做的是使用 for 循环和范围来获取单词 2 中每个字母第一次出现在单词 1 中的时间的索引,但在这种情况下它不起作用:
>>> within('aaaacadgt', 'cat')
因为 a 的索引会给我第一个索引并导致返回值为 False,即使它是 True。
请注意,除了字符串之外,我不能使用任何方法。
所以没有列表、字典、元组等。
解决方案
使用正则表达式有一种有趣的方法来处理这个问题:
import re
def within(big, small):
# we will do this with a regular expression, checking for each character in order,
# with any number of any kind of character in between them, and before/after
# '.*' will get this.
rexp = '.*' + '.*'.join(re.escape(small)) + '.*'
# then, we just see if the regex matches
return (re.match(rexp, big) is not None)
也就是说,也可以不用正则表达式。考虑一种递归方法:
def within(big, small):
# base case: return True on an empty string
if small == '':
return True
# Find the first occurrence in `big` of the first character
try:
idx = big.index(small[0])
# If it's there, then search for the next character, after that point
# by using string slicing
return within(big[(idx + 1):], small[1:])
except Indexerror:
# If the first character of small is not in big, then small can't occur in big.
return False
通过以某种方式跟踪索引,可以将其推广为非递归方法。它与您所做的类似 - 但它切断了字符串的前面以避免您遇到错误。
推荐阅读
- powershell - 如何在 powershell 脚本中使用 SSISDeploy 命令
- angular - Angular + Jasmine + Karma 测试'window.location.href'
- c# - 如何在 SQLXML 中调整服务器协议和哈希
- java - 与 OkHttp 拦截器作斗争
- angular - Angular 10 中的根级服务如何与组件级服务交互
- css - 具有行跨度的 td 中 css 类的奇怪行为(Angular)
- python - 有没有办法排除在 IntelliSense 中自动完成的参数?
- javascript - React - 2 个相互依赖的输入字段 - 无限循环
- python - Python 3 等效于 string.maketrans('','')
- swagger-ui - 使用 swagger UI 进行生产使用